Java Hibernate JPA持久性异常
我试图基于一组给定的JUnit测试测试我的hibernate映射。但是,以下测试失败Java Hibernate JPA持久性异常,java,hibernate,jpa,exception,Java,Hibernate,Jpa,Exception,我试图基于一组给定的JUnit测试测试我的hibernate映射。但是,以下测试失败 @Test public void testEntity3Constraint() { expectedException.expect(PersistenceException.class); expectedException.expectCause(isA(ConstraintViolationException.class)); EntityTransaction tx = e
@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
Expected:(javax.persistence.PersistenceException的实例和带有原因的异常是
org.hibernate.exception.ConstraintViolationException的实例)
但是:exception with cause是org.hibernate.exception.ConstraintViolationException cause的一个实例
是org.hibernate.persistentObject异常
正如您所看到的,约束冲突和持久性异常在实例和原因方面进行了交换。调用entitymanager.persist
时引发异常。如何获得预期的异常
我无法更改预期的异常,也不想更改。我需要找到一种方法来获得测试预期的异常
提前谢谢 您期望的是
javax.persistence.PersistenceException
但是得到一个类似但不同的
org.hibernate.PersistentObjectException
只需更改测试中预期的异常。为什么不能执行
expectedException.expect(ConstraintViolationException.class)代码>,我遗漏了什么吗?测试已经给出,我不允许修改它们,所以现在我正在寻找一种方法来获得测试所需的异常谢谢,我本来可以自己做的。我需要与之相反的东西。我想更改抛出的异常,以便与预期的异常相匹配。然后,您必须创建自己的EntityManager。