Exceptions and Junit
Figure 520. Expected exceptions in Junit
@Test(expected = FileAlreadyExistsException.class) public void copyFile() throws IOException { final Path source = Paths.get("/tmp/source.txt"), dest = Paths.get("/tmp/dest.txt"); Files.copy(source, dest); // May work. Files.copy(source, dest); // Failure: FileAlreadyExistsException }
No. 178
Expected exception test failure
Q: |
We reconsider: @Test(expected = FileAlreadyExistsException.class) public void copyFile() throws IOException { final Path source = Paths.get("/tmp/source.txt"), dest = Paths.get("/tmp/dest.txt"); Files.copy(source, dest); // May work. Files.copy(source, dest); // Failure: FileAlreadyExistsException } Modify this code by catching the exception inside
|
A: |
We catch the exception in question: @Test(expected = FileAlreadyExistsException.class) public void copyFile() throws IOException { final Path source = Paths.get("/tmp/source.txt"), dest = Paths.get("/tmp/dest.txt"); try { Files.copy(source, dest); // May work. Files.copy(source, dest); // Failure: FileAlreadyExistsException } catch (final FileAlreadyExistsException e) { System.out.println("Destination file already exists"); } } Since we swallow the Destination file already exists java.lang.AssertionError: Expected exception: java.nio.file.FileAlreadyExistsException |