Merge pull request #3951 from bahti/BAEL-1663

asserting exceptions in junit4 and junit5 code sample added
This commit is contained in:
Loredana Crusoveanu 2018-04-09 10:15:59 +03:00 committed by GitHub
commit a7d878ca75
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 47 additions and 0 deletions

View File

@ -0,0 +1,23 @@
package com.baeldung.exception;
import static org.junit.jupiter.api.Assertions.assertThrows;
import org.junit.jupiter.api.Test;
public class ExceptionAssertionTest {
@Test
public void whenExceptionThrown_thenAssertionSucceeds() {
String test = null;
assertThrows(NullPointerException.class, () -> {
test.length();
});
}
@Test
public void whenDerivedExceptionThrown_thenAssertionSucceds() {
String test = null;
assertThrows(RuntimeException.class, () -> {
test.length();
});
}
}

View File

@ -0,0 +1,24 @@
package com.baeldung.migration.junit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
public class ExceptionAssertionTest {
@Rule
public ExpectedException exceptionRule = ExpectedException.none();
@Test(expected = NullPointerException.class)
public void whenExceptionThrown_thenExpectationSatisfied() {
String test = null;
test.length();
}
@Test
public void whenExceptionThrown_thenRuleIsApplied() {
exceptionRule.expect(NumberFormatException.class);
exceptionRule.expectMessage("For input string");
Integer.parseInt("1a");
}
}