2

データベースの一意性制約に違反する単体テストがあります。私が実行すると:

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

の実際のクラスはeですjavax.persistence.PersistenceException。OK、テスト コードを次のように更新します。

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

最善の方法ではありませんが、単体テストには適しています!

    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

エンティティー・マネージャーでJPA ベンダー・アダプター ( setJpaVendorAdapter ) を設定しましたか? それがなければ、Spring は Hibernate 固有の例外を解釈しないため、代わりに一般的な例外をスローします。

于 2013-05-22T05:50:33.890 に答える