有一个违反数据库唯一约束的单元测试。当我跑步时:
try {
someDao.save(employee2);
} catch (Exception e) {
Class clazz = e.getClass();
System.out.println( clazz.getName());
}
e
的实际类别是javax.persistence.PersistenceException
。好的,我将测试代码更新为:
exception.expect(PersistenceException.class);
someDao.save(employee2);
但是测试失败,并显示以下错误:
Expected: an instance of javax.persistence.PersistenceException
but: <org.junit.internal.runners.model.MultipleFailureException: There were 2 errors:
javax.persistence.PersistenceException(org.hibernate.exception.ConstraintViolationException: could not execute statement)
org.springframework.transaction.TransactionSystemException(Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly)> is a org.junit.internal.runners.model.MultipleFailureException
Stacktrace was: org.junit.internal.runners.model.MultipleFailureException: There were 2 errors:
javax.persistence.PersistenceException(org.hibernate.exception.ConstraintViolationException: could not execute statement)
org.springframework.transaction.TransactionSystemException(Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Transaction marked as rollbackOnly)
我尝试了以下所有例外,但没有帮助:
exception.expect(org.springframework.transaction.TransactionSystemException.class);
exception.expect(org.hibernate.exception.ConstraintViolationException.class);
违反数据库约束时应该期待哪个异常?
最佳答案
这不是最佳方法,但对单元测试很有用!
try
{
someDao.save(employee2);
} catch (Exception e) {
System.out.println(e.getMessage());
}
假设您得到一些输出,然后将其存储在错误字符串中。记下这一点并按如下所示更新您的测试用例
@Test
public void testException() {
try {
someDao.save(employee2);
fail("expected an exception");
} catch (PersistenceException ex) {
assertEquals(Error, ex.getMessage());
}
}