Exceptions and Junit
@Test()
public void testApp() {
NoSuchFileException exception =
Assertions.assertThrowsExactly(NoSuchFileException.class, () -> {
final Path
sourcePath = Paths.get("/tmp/noexist.txt"),
destPath = Paths.get("/tmp/copy.java");
Files.copy(sourcePath, destPath);
}
);
Assertions.assertEquals("/tmp/noexist.txt", exception.getMessage());
}See Junit 6 Exception Handling
No. 178
Expected exception test failure
|
Q: |
We reconsider Figure 543, “Expected exceptions in Junit ”. Modify
that code by enclosing the |
|
A: |
We catch the exception in question: @Test()
public void testApp() {
NoSuchFileException exception =
Assertions.assertThrowsExactly(NoSuchFileException.class, () -> {
final Path
sourcePath = Paths.get("/tmp/noexist.txt"),
destPath = Paths.get("/tmp/copy.java");
try {
Files.copy(sourcePath, destPath);
} catch (IOException e) {
System.out.println("Source file does not exist");
}
}
);
Assertions.assertEquals("/tmp/noexist.txt", exception.getMessage());
}Since we swallow the "Source file does not exist" org.opentest4j.AssertionFailedError: Expected java.nio.file.NoSuchFileException to be thrown, but nothing was thrown. This off course is the expected test behavior. |
