的ExpectedException JUnit中?
-
20-08-2019 - |
题
是否有一个相当于NUnit的的的ExpectedException或Assert.Throws <>在JUnit?
解决方案
junit4:
@Test(expected = org.dom4j.DocumentException.class)
void shouldThrowException() {
getFile(null);
}
junit3:
void testShouldThrowException() {
try {
getFile(null);
fail("Expected Exception DocumentException");
} catch(DocumentException e) {}
}
其他提示
您也可能会考虑看看的ExpectedException类,它提供了更丰富的异常匹配。
https://github.com/junit-team/junit/wiki /异常测试
您不仅可以匹配的异常类,但你也可以将自定义的匹配到它的消息。
如果您正在使用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.'
}
不隶属于 StackOverflow