Exceptions and Junit

Figure 543. Expected exceptions in Junit Slide presentation
@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


exercise No. 178

Expected exception test failure

Q:

We reconsider Figure 543, “Expected exceptions in Junit. Modify that code by enclosing the Files.copy(...) statement in a try {...} catch {...} block catching the exception yourself. What do you observe on test execution?

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 NoSuchFileException ourselves it is no longer being thrown. Due to the assertThrowsExactly(...) method still expecting this exception test execution now fails:

"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.