File: AssertThrowsMultipleStatements.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 (34 lines) | stat: -rw-r--r-- 900 bytes parent folder | download | duplicates (2)
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
If the body of the lambda passed to `assertThrows` contains multiple statements,
execution of the lambda will stop at the first statement that throws an
exception and all subsequent statements will be ignored.

This means that:

*   Any set-up logic in the lambda will cause the test to incorrectly pass if it
    throws the expected exception.
*   Any assertions that run after the statement that throws will never be
    executed.

Don't do this:

```java
assertThrows(
    UnsupportedOperationException.class,
    () -> {
        AppendOnlyList list = new AppendOnlyList();
        list.add(0, "a");
        list.remove(0);
        assertThat(list).containsExactly("a");
    });
```

Do this instead:

```java
AppendOnlyList list = new AppendOnlyList();
list.add(0, "a");
assertThrows(
    UnsupportedOperationException.class,
    () -> list.remove(0));
assertThat(list).containsExactly("a");
```