我有这个单元测试,尽管抛出了异常,但总体测试失败,尽管它的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");
}
}
请查看JUnit Wiki:https://github.com/junit-team/junit/wiki/Exception-testing它列出了测试异常的不同方法。
您可以同时具有@Test(expected = SomeException.class)
或使用try...catch
。您不能同时使用它们。
[当您声明要预期将抛出某个异常的测试时,如果您在测试中捕获了该异常,就不会抛出该异常,是吗?
尽管我还没有尝试过,但是您可以尝试从catch块中重新抛出异常。
catch(AutoGenerateStringIdException e){
assertEquals(e.getMessage(), "Cannot auto-generate String @Id");
throw e;
}
如果测试中预期会出现异常,则不应捕获它。只需删除try / catch并观看,会发生什么。