【发布时间】: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