Hibernate JPA持久性异常

时间:2017-03-25 20:56:31

标签: java hibernate jpa exception

我试图根据一组给定的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

正如您所看到的,Constraint Violations和Persistence Exceptions在实例和原因方面进行了交换。我打电话给entitymanager.persist时会抛出异常。我怎样才能获得预期的例外?

我不能改变预期的异常,也不想改变。我需要找到一种方法来获得测试所期望的异常。

提前致谢!

1 个答案:

答案 0 :(得分:0)

您期待javax.persistence.PersistenceException
但得到一个类似但不同的org.hibernate.PersistentObjectException

只需更改测试中您期望的例外情况。