|
3 | 3 | import static org.assertj.core.api.Assertions.assertThatThrownBy; |
4 | 4 | import static org.assertj.core.api.Assertions.assertThat; |
5 | 5 | import static org.assertj.core.api.Assertions.assertThatExceptionOfType; |
| 6 | +import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException; |
| 7 | +import static org.assertj.core.api.Assertions.assertThatIllegalStateException; |
| 8 | +import static org.assertj.core.api.Assertions.assertThatIOException; |
| 9 | +import static org.assertj.core.api.Assertions.assertThatNullPointerException; |
6 | 10 | import static org.assertj.core.api.Assertions.catchThrowable; |
7 | 11 |
|
| 12 | +import java.io.IOException; |
| 13 | +import java.util.ArrayList; |
| 14 | +import java.util.Arrays; |
| 15 | + |
8 | 16 | import org.junit.Test; |
9 | 17 |
|
10 | 18 | public class Java8StyleAssertions { |
11 | 19 |
|
12 | 20 | @Test |
13 | | - public void whenDividingByZero_thenArithmeticException() { |
| 21 | + public void whenGettingOutOfBoundsItem_thenIndexOutOfBoundsException() { |
14 | 22 | assertThatThrownBy(() -> { |
15 | | - int numerator = 10; |
16 | | - int denominator = 0; |
17 | | - int quotient = numerator / denominator; |
18 | | - }).isInstanceOf(ArithmeticException.class) |
19 | | - .hasMessageContaining("/ by zero"); |
| 23 | + ArrayList<String> myStringList = new ArrayList<String>(Arrays.asList("Strine one", "String two")); |
| 24 | + myStringList.get(2); |
| 25 | + }).isInstanceOf(IndexOutOfBoundsException.class) |
| 26 | + .hasMessageStartingWith("Index: 2") |
| 27 | + .hasMessageContaining("2") |
| 28 | + .hasMessageEndingWith("Size: 2") |
| 29 | + .hasMessageContaining("Index: 2, Size: 2") |
| 30 | + .hasMessage("Index: %s, Size: %s", 2, 2) |
| 31 | + .hasMessageMatching("Index: \\d+, Size: \\d+") |
| 32 | + .hasNoCause(); |
| 33 | + } |
20 | 34 |
|
| 35 | + @Test |
| 36 | + public void whenWrappingException_thenCauseInstanceOfWrappedExceptionType() { |
| 37 | + assertThatThrownBy(() -> { |
| 38 | + try { |
| 39 | + throw new IOException(); |
| 40 | + } catch (IOException e) { |
| 41 | + throw new RuntimeException(e); |
| 42 | + } |
| 43 | + }).isInstanceOf(RuntimeException.class) |
| 44 | + .hasCauseInstanceOf(IOException.class) |
| 45 | + .hasStackTraceContaining("java.io.IOException"); |
| 46 | + } |
| 47 | + |
| 48 | + @Test |
| 49 | + public void whenDividingByZero_thenArithmeticException() { |
21 | 50 | assertThatExceptionOfType(ArithmeticException.class).isThrownBy(() -> { |
22 | 51 | int numerator = 10; |
23 | 52 | int denominator = 0; |
24 | 53 | int quotient = numerator / denominator; |
25 | 54 | }) |
26 | 55 | .withMessageContaining("/ by zero"); |
27 | 56 |
|
28 | | - // BDD style: |
| 57 | + // Alternatively: |
29 | 58 |
|
30 | 59 | // when |
31 | 60 | Throwable thrown = catchThrowable(() -> { |
|
0 commit comments