2

有一个违反数据库唯一约束的单元测试。当我运行时:

try {
    someDao.save(employee2);
} catch (Exception e) {
    Class clazz = e.getClass();
    System.out.println( clazz.getName());
}

的实际类ejavax.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);

当违反数据库约束时,我应该期待哪个异常?

4

3 回答 3

0

您是否在实体管理器上设置了 JPA 供应商适配器 ( setJpaVendorAdapter )?没有它,Spring 不会解释 Hibernate 特定的异常,而是抛出通用的异常。

于 2013-05-22T05:50:33.890 回答
0

不是最好的方法,但对单元测试很有用!

    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());
    }
}
于 2013-05-22T05:48:25.433 回答
0

异常的层次结构是:TransactionSystemException getCause() -> RollBackException getCause() -> ConstraintViolationException

所以你可以尝试:

    try {
        taskRepository.save(task);
    } catch (TransactionSystemException e) {
        assertThat("name must not be null", e.getCause().getCause(), instanceOf(ConstraintViolationException.class));
    }   

这并不能保证哪个约束失败,但考虑到测试的范围,它可能就足够了。您必须深入研究约束错误以获得更具体的细节

于 2018-05-02T03:27:16.983 回答