8

jUnit 中是否有与 NUnit 的 ExpectedException 或 Assert.Throws<> 等价的东西?

4

3 回答 3

11

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

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

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

于 2010-11-24T09:53:16.960 回答
7

junit4:

@Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
    getFile(null);
}

junit3:

void testShouldThrowException() {
    try {
      getFile(null);
      fail("Expected Exception DocumentException");
    } catch(DocumentException e) {}
}
于 2009-06-27T11:40:32.537 回答
2

如果您使用 Groovy 进行 junit 测试,您可以使用shouldFail

这是一个使用 junit3 样式的示例:

void testShouldThrowException() {
    def message = shouldFail(DocumentException) {
        documentService.getFile(null)
    }
    assert message == 'Document could not be saved because it ate the homework.'
}
于 2012-03-29T23:24:22.200 回答