我应该期待哪个例外

时间:2013-05-22 05:29:47

标签: java spring testing datasource

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

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);

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

3 个答案:

答案 0 :(得分: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());
    }
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

例外的层次结构是: TransactionSystemException getCause() - &gt; RollBackException getCause() - &gt; ConstraintViolationException

所以你可以试试:

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

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