jUnit中的ExpectedException?

rip*_*234 8 junit nunit assertions expected-exception

是否在jUnit中等效于NUnit的ExpectedException或Assert.Throws <>?

Mac*_*łas 11

您还可以考虑查看ExpectedException类,它提供更丰富的异常匹配.

https://github.com/junit-team/junit/wiki/Exception-testing

您不仅可以匹配异常类,还可​​以将自定义匹配器应用于其消息.


Tim*_*Tim 7

junit4:

@Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
    getFile(null);
}
Run Code Online (Sandbox Code Playgroud)

junit3:

void testShouldThrowException() {
    try {
      getFile(null);
      fail("Expected Exception DocumentException");
    } catch(DocumentException e) {}
}
Run Code Online (Sandbox Code Playgroud)