更新: JUnit5 对异常测试进行了改进:assertThrows
.
以下示例来自:Junit 5 用户指南
@Test
void exceptionTesting() {
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("a message");
});
assertEquals("a message", exception.getMessage());
}
使用 JUnit 4 的原始答案。
有几种方法可以测试是否引发了异常。我还在我的帖子How to write great unit tests with JUnit中讨论了以下选项
设置expected
参数@Test(expected = FileNotFoundException.class)
。
@Test(expected = FileNotFoundException.class)
public void testReadFile() {
myClass.readFile("test.txt");
}
使用try
catch
public void testReadFile() {
try {
myClass.readFile("test.txt");
fail("Expected a FileNotFoundException to be thrown");
} catch (FileNotFoundException e) {
assertThat(e.getMessage(), is("The file test.txt does not exist!"));
}
}
用ExpectedException
规则测试。
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void testReadFile() throws FileNotFoundException {
thrown.expect(FileNotFoundException.class);
thrown.expectMessage(startsWith("The file test.txt"));
myClass.readFile("test.txt");
}
您可以在 JUnit4 wiki 中阅读有关异常测试的更多信息,以获取 Exception testing和bad.robot - Expecting Exceptions JUnit Rule。