如何拦截并处理java测试约束违规(FOREIGN KEY约束失败)。我有一个数据库,我在那里设置了删除记录的约束。在测试过程中,约束被触发并终止测试。因此,测试没有通过。如何做到让抛出禁止删除的消息时测试通过
try {
new RowName.delete(new RowName.get(1));
// constraint is triggered when deleting
} catch (Exception e) {
??????????
}
org.sqlite.SQLiteException: [SQLITE_CONSTRAINT] 由于违反约束而中止(FOREIGN KEY 约束失败)
最佳答案
我不能 100% 确定这就是您所要求的,但我们开始吧:
try {
new RowName.delete(new RowName.get(1));
fail("It should not be possible to call .delete. DB should throw an exception since this is a violation of a constraint.");
} catch (org.sqlite.SQLiteException e) {
// Just continue. We expect an SQLiteException since the test data has a
// constraint that forbids the .delete.
}
// Any other exception that is thrown will cause the test to fail which
// is what we want. The SQLiteException is expected since you forced it
// to happen. Other exceptions have to be examined and handled.
因此,如果 .delete 不正常并因此数据库引发异常,则您的测试将通过。但是,如果 .delete 成功,则说明您的数据库或测试数据出现问题,然后 failed("...") 将使您的测试用例失败。
关于java - 如何在java约束测试违规中拦截并处理(FOREIGN KEY约束失败),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56825111/