我有这个单元测试,整个测试由于抛出的异常而失败,尽管它的expected
@Test(expected = AutoGenerateStringIdException.class)
public void testPut_shouldThrowException(){
RootEntity rootObject = new RootEntity();
// Some codes here
try {
Key key = store.put(rootObject);
} catch(AutoGenerateStringIdException e){
assertEquals(e.getMessage(), "Cannot auto-generate String @Id");
}
}发布于 2014-04-29 19:49:41
请看一下JUnit wiki:https://github.com/junit-team/junit/wiki/Exception-testing,它列出了用于测试异常的不同方法。
发布于 2014-04-29 12:45:24
您可以使用@Test(expected = SomeException.class),也可以像正在做的那样使用try...catch。你不能同时使用它们。
当您声明一个测试预期会抛出某个异常时,如果在测试中捕获它,它就不会被抛出,对吗?
虽然我还没有试过,但是您可以尝试从catch块重新抛出异常。
catch(AutoGenerateStringIdException e){
assertEquals(e.getMessage(), "Cannot auto-generate String @Id");
throw e;
}发布于 2014-04-29 12:45:16
如果期望在测试中出现异常,则不应捕获它。只要移除尝试/捕捉和观察,发生了什么。
https://stackoverflow.com/questions/23364989
复制相似问题