我正在尝试根据一组给定的 JUnit 测试来测试我的 hibernate 映射。然而,以下测试失败了。
@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
时抛出异常。如何获得预期的异常?
我无法更改预期的异常,我也不想更改。我需要找到一种方法来获取测试预期的异常。
提前致谢!
最佳答案
您期待 javax.persistence.PersistenceException
但得到一个相似但不同的 org.hibernate.PersistentObjectException
。
只需更改您在测试中期望的异常。
关于java - Hibernate JPA 持久性异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43021866/