asserting exceptions in junit4 and junit5 code sample added

This commit is contained in:
bahti 2018-04-08 13:03:40 +03:00
parent 43365351c3
commit e045189ab7
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");
}
}