【问题标题】:Hibernate JPA Persistence ExceptionHibernate JPA 持久性异常
【发布时间】:2017-08-18 17:05:24
【问题描述】:

我正在尝试根据一组给定的 JUnit 测试来测试我的休眠映射。但是下面的测试失败了。

@Test
public void testEntity3Constraint() {
    expectedException.expect(PersistenceException.class);
    expectedException.expectCause(isA(ConstraintViolationException.class));

    EntityTransaction tx = em.getTransaction();
    tx.begin();
    try {
        // Entity #3
        IUplink ent3_1 = daoFactory.getUplinkDAO().findById(testData.entity3_1Id);
        ent3_1.setName(TestData.N_ENT3_2);
        em.persist(ent3_1);
        em.flush();

    } finally {
        tx.rollback();
    }
}

这是我得到的例外:

Expected: (an instance of javax.persistence.PersistenceException and exception with cause is an 
     instance of org.hibernate.exception.ConstraintViolationException)
but: exception with cause is an instance of org.hibernate.exception.ConstraintViolationException cause 
     <org.hibernate.PersistentObjectException: detached entity passed to persist: dst.ass1.jpa.model.impl.UplinkImpl> 
     is a org.hibernate.PersistentObjectException

如您所见,约束违反和持久性异常在实例和原因方面进行了交换。当我调用entitymanager.persist 时抛出异常。如何获得预期的异常?

我无法更改预期的异常,也不想更改。我需要找到一种方法来获取测试预期的异常。

提前致谢!

【问题讨论】:

  • 你为什么不能expectedException.expect(ConstraintViolationException.class);,我错过了什么吗?
  • 测试已经给出,我不能更改它们,所以现在我正在寻找一种方法来获得测试所需的异常

标签: java hibernate jpa exception


【解决方案1】:

你期待javax.persistence.PersistenceException
但得到一个相似但不同的org.hibernate.PersistentObjectException。

只需更改您在测试中期望的异常。

【讨论】:

  • 谢谢,我可以自己做。我需要相反的。我想更改抛出的异常以匹配预期的异常
  • 你必须创建自己的EntityManager。
猜你喜欢
  • 2014-09-08
  • 2013-11-15
  • 1970-01-01
  • 2010-10-24
  • 2018-01-02
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
  • 1970-01-01
相关资源
最近更新 更多