<>Update: 日特5改进了例外情况测试:assertThrows
。
The following example is from: Junit 5 User Guide
import static org.junit.jupiter.api.Assertions.assertThrows;
@Test
void exceptionTesting() {
IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {
throw new IllegalArgumentException("a message");
});
assertEquals("a message", exception.getMessage());
}
www.un.org/Depts/DGACM/index_spanish.htm 初步答案:
有几个办法可以检验存在一种例外。 我还在我的。 • 如何与Junnit进行大单位测试
Set of the expected
para amount :Release@(expected = file NotFoundException.class)
。
@Test(expected = FileNotFoundException.class)
public void testReadFile() {
myClass.readFile("test.txt");
}
采用<条码><%/代码> > 副渔获物/代码>
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");
}
可在和bad.robot - Expecting Statelessnessions JUnit Rule。