gpt4 book ai didi

java - 我应该期待哪个异常(exception)

转载 作者:行者123 更新时间:2023-11-28 20:15:51 25 4
gpt4 key购买 nike

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

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)情况,但没有帮助:

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

假设您得到了一些输出。让我们将其存储在Error 字符串中。记下这一点并按如下方式更新您的测试用例

@Test
public void testException() {
try {
someDao.save(employee2);
fail("expected an exception");
} catch (PersistenceException ex) {
assertEquals(Error, ex.getMessage());
}
}

关于java - 我应该期待哪个异常(exception),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16684123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com