ExpectedExceptionChecker
Prefer assertThrows to ExpectedException

Severity
WARNING

The problem

Any additional statements after the statement that is expected to throw will never be executed in a passing test. This can lead to inappropriately passing tests where later incorrect assertions are skipped by the thrown exception. For instance, the final assertion in the following example will never be executed if the call throws as expected.

@Test
public void testRemoveFails() {
  AppendOnlyList list = new AppendOnlyList();
  list.add(0, "a");
  thrown.expect(UnsupportedOperationException.class);
  thrown.expectMessage("hello");
  list.remove(0); // throws
  assertThat(list).hasSize(1); // never executed
}

To avoid this issue, prefer JUnit’s assertThrows() API:

import static org.junit.Assert.assertThrows;

@Test
public void testRemoveFails() {
  AppendOnlyList list = new AppendOnlyList();
  list.add(0, "a");
  UnsupportedOperationException thrown = assertThrows(
      UnsupportedOperationException.class,
      () -> {
        list.remove(0);
      });
  assertThat(thrown).hasMessageThat().contains("hello");
  assertThat(list).hasSize(1);
}

Suppression

Suppress false positives by adding the suppression annotation @SuppressWarnings("ExpectedExceptionChecker") to the enclosing element.