File tree Expand file tree Collapse file tree
src/test/java/com/baeldung/testing/assertj/exceptions Expand file tree Collapse file tree Original file line number Diff line number Diff line change 173173 <jacoco .version>0.7.7.201606060606</jacoco .version>
174174 <guava .version>21.0</guava .version>
175175 <assertj-guava .version>3.1.0</assertj-guava .version>
176- <assertj-core .version>3.6.1 </assertj-core .version>
176+ <assertj-core .version>3.9.0 </assertj-core .version>
177177 <assertj-generator .version>2.1.0</assertj-generator .version>
178178 <truth .version>0.32</truth .version>
179179 <jUnitParams .version>1.1.0</jUnitParams .version>
Original file line number Diff line number Diff line change 1+ package com .baeldung .testing .assertj .exceptions ;
2+
3+ import static org .assertj .core .api .Assertions .assertThat ;
4+ import static org .assertj .core .api .Assertions .fail ;
5+ import static org .assertj .core .api .Assertions .failBecauseExceptionWasNotThrown ;
6+
7+ import org .junit .Test ;
8+
9+ public class Java7StyleAssertions {
10+
11+ @ Test
12+ public void whenDividingByZero_thenArithmeticException () {
13+ try {
14+ int numerator = 10 ;
15+ int denominator = 0 ;
16+ int quotient = numerator / denominator ;
17+ fail ("ArithmeticException expected because dividing by zero yields an ArithmeticException." );
18+ failBecauseExceptionWasNotThrown (ArithmeticException .class );
19+ } catch (Exception e ) {
20+ assertThat (e ).hasMessage ("/ by zero" );
21+ assertThat (e ).isInstanceOf (ArithmeticException .class );
22+ }
23+ }
24+ }
Original file line number Diff line number Diff line change 1+ package com .baeldung .testing .assertj .exceptions ;
2+
3+ import static org .assertj .core .api .Assertions .assertThatThrownBy ;
4+ import static org .assertj .core .api .Assertions .assertThat ;
5+ import static org .assertj .core .api .Assertions .assertThatExceptionOfType ;
6+ import static org .assertj .core .api .Assertions .catchThrowable ;
7+
8+ import org .junit .Test ;
9+
10+ public class Java8StyleAssertions {
11+
12+ @ Test
13+ public void whenDividingByZero_thenArithmeticException () {
14+ assertThatThrownBy (() -> {
15+ int numerator = 10 ;
16+ int denominator = 0 ;
17+ int quotient = numerator / denominator ;
18+ }).isInstanceOf (ArithmeticException .class )
19+ .hasMessageContaining ("/ by zero" );
20+
21+ assertThatExceptionOfType (ArithmeticException .class ).isThrownBy (() -> {
22+ int numerator = 10 ;
23+ int denominator = 0 ;
24+ int quotient = numerator / denominator ;
25+ })
26+ .withMessageContaining ("/ by zero" );
27+
28+ // BDD style:
29+
30+ // when
31+ Throwable thrown = catchThrowable (() -> {
32+ int numerator = 10 ;
33+ int denominator = 0 ;
34+ int quotient = numerator / denominator ;
35+ });
36+
37+ // then
38+ assertThat (thrown ).isInstanceOf (ArithmeticException .class )
39+ .hasMessageContaining ("/ by zero" );
40+
41+ }
42+ }
You can’t perform that action at this time.
0 commit comments