Skip to content

Commit a7d878c

Browse files
authored
Merge pull request eugenp#3951 from bahti/BAEL-1663
asserting exceptions in junit4 and junit5 code sample added
2 parents c0ab2f7 + e045189 commit a7d878c

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.exception;
2+
3+
import static org.junit.jupiter.api.Assertions.assertThrows;
4+
5+
import org.junit.jupiter.api.Test;
6+
7+
public class ExceptionAssertionTest {
8+
@Test
9+
public void whenExceptionThrown_thenAssertionSucceeds() {
10+
String test = null;
11+
assertThrows(NullPointerException.class, () -> {
12+
test.length();
13+
});
14+
}
15+
16+
@Test
17+
public void whenDerivedExceptionThrown_thenAssertionSucceds() {
18+
String test = null;
19+
assertThrows(RuntimeException.class, () -> {
20+
test.length();
21+
});
22+
}
23+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
package com.baeldung.migration.junit4;
2+
3+
import org.junit.Rule;
4+
import org.junit.Test;
5+
import org.junit.rules.ExpectedException;
6+
7+
public class ExceptionAssertionTest {
8+
9+
@Rule
10+
public ExpectedException exceptionRule = ExpectedException.none();
11+
12+
@Test(expected = NullPointerException.class)
13+
public void whenExceptionThrown_thenExpectationSatisfied() {
14+
String test = null;
15+
test.length();
16+
}
17+
18+
@Test
19+
public void whenExceptionThrown_thenRuleIsApplied() {
20+
exceptionRule.expect(NumberFormatException.class);
21+
exceptionRule.expectMessage("For input string");
22+
Integer.parseInt("1a");
23+
}
24+
}

0 commit comments

Comments
 (0)