Testing for Exceptions

When testing for the presence of an exception in the test code, either JUnit or Cucumber step definitions, you can use the following two methods. The first method catches the exception and checks that the error message is correct. If the exception is not thrown by the test code, then the tests fails by using the fail method.
@Test
public void testSomething() {
  ...
  try {
    // Some code that is expected to 
    // throw OperationNotAllowedException
    assertFalse(libApp.adminLoggedIn());
    libApp.addBook(b);
    fail("Expected OperationNotAllowedException to be thrown");
  } catch (OperationNotAllowedException e) {
    // Check, e.g., that the error message is correctly set
    assertEquals(expected, e.getMessage());
  }
}
An alternative version is to use an annotation to indicate that it is expected that the test method throws an exception. The disadvantage is, that is not possible to check if the exception has the correct structure, e.g., has the correct error message.
@Test(expected=OperationNotAllowedException.class)
public void testSomething() {...}


On to Compiler error: Unreachable catch block Part of User-defined Exceptions
Hubert Baumeister
April 23, 2018