有一个违反数据库唯一约束的单元测试。当我运行时:
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);
当违反数据库约束时,我应该期待哪个异常?