[英]Test fails because of Exception thrown
I have this unit test, that the overall test fails because of the exceptions that is thrown, although its expected
:我有这个单元测试,整体测试由于抛出异常而失败,尽管它是
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");
}
}
You can either have @Test(expected = SomeException.class)
or use a try...catch
as you're doing.您可以使用
@Test(expected = SomeException.class)
或使用try...catch
。 You can't use both of them at the same time.您不能同时使用它们。
When you declare a test to expect a certain exception to be thrown and if you catch it within the test, it wouldn't be thrown, would it?当你声明一个测试期望抛出某个异常时,如果你在测试中捕捉到它,它就不会被抛出,是吗?
Although I haven't tried it, you could try re-throwing the exception from the catch block.虽然我还没有尝试过,但您可以尝试从 catch 块中重新抛出异常。
catch(AutoGenerateStringIdException e){
assertEquals(e.getMessage(), "Cannot auto-generate String @Id");
throw e;
}
If exception is expected in test, you should not catch it.如果在测试中预期出现异常,则不应捕获它。 Just remove try/catch and watch, what happens.
只需删除 try/catch 并观察会发生什么。
请查看 JUnit wiki: https : //github.com/junit-team/junit/wiki/Exception-testing它列出了测试异常的不同方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.