diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionTest.java new file mode 100644 index 0000000000..f97e2ba9c7 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/exception/ExceptionAssertionTest.java @@ -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(); + }); + } +} \ No newline at end of file diff --git a/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionTest.java b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionTest.java new file mode 100644 index 0000000000..6cd2559f57 --- /dev/null +++ b/testing-modules/junit-5/src/test/java/com/baeldung/migration/junit4/ExceptionAssertionTest.java @@ -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"); + } +}