ExpectedExceptionChecker
Calls to ExpectedException#expect should always be followed by exactly one statement.

Category
JUNIT
Severity
WARNING
Maturity

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() or expectThrows() API:

import static org.junit.Assert.expectThrows;

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

Suppression

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