![](/img/trans.png)
[英]Junit test fails when fetching Exception object stored in a class, not thrown
[英]Test fails because of Exception thrown
我有这个单元测试,整体测试由于抛出异常而失败,尽管它是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");
}
}
您可以使用@Test(expected = SomeException.class)
或使用try...catch
。 您不能同时使用它们。
当你声明一个测试期望抛出某个异常时,如果你在测试中捕捉到它,它就不会被抛出,是吗?
虽然我还没有尝试过,但您可以尝试从 catch 块中重新抛出异常。
catch(AutoGenerateStringIdException e){
assertEquals(e.getMessage(), "Cannot auto-generate String @Id");
throw e;
}
如果在测试中预期出现异常,则不应捕获它。 只需删除 try/catch 并观察会发生什么。
请查看 JUnit wiki: https : //github.com/junit-team/junit/wiki/Exception-testing它列出了测试异常的不同方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.