Exceptions and Junit

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

exercise No. 176

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 copyFile() using try {...} catch {...}. Then execute the test. What do you observe?

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 FileAlreadyExistsException ourselves it is no longer being thrown. Due to the @Test(expected = FileAlreadyExistsException.class) annotation test execution now fails:

Destination file already exists

java.lang.AssertionError: Expected exception: java.nio.file.FileAlreadyExistsException