由于抛出异常,测试失败

问题描述 投票:0回答:3

我有这个单元测试,尽管抛出了异常,但总体测试失败,尽管它的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"); 
    }
}
java junit junit4
3个回答
0
投票

请查看JUnit Wiki:https://github.com/junit-team/junit/wiki/Exception-testing它列出了测试异常的不同方法。


3
投票

您可以同时具有@Test(expected = SomeException.class)或使用try...catch。您不能同时使用它们。

[当您声明要预期将抛出某个异常的测试时,如果您在测试中捕获了该异常,就不会抛出该异常,是吗?

尽管我还没有尝试过,但是您可以尝试从catch块中重新抛出异常。

catch(AutoGenerateStringIdException e){
    assertEquals(e.getMessage(), "Cannot auto-generate String @Id"); 
    throw e;
}

0
投票

如果测试中预期会出现异常,则不应捕获它。只需删除try / catch并观看,会发生什么。

© www.soinside.com 2019 - 2024. All rights reserved.