File: ExpectedExceptionChecker.md

package info (click to toggle)
error-prone-java 2.18.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 23,204 kB
  • sloc: java: 222,992; xml: 1,319; sh: 25; makefile: 7
file content (39 lines) | stat: -rw-r--r-- 1,189 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39

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.

```java
@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:

```java
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);
}
```

[`ExpectedException`]: http://junit.org/junit4/javadoc/latest/org/junit/rules/ExpectedException.html