In this example, we take a look at a JUnit example of failing a test on NullPointerException.
Code Example:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
public class JunitExceptionExample {
@Test
public void test() {
try {
String str = null;
str.toLowerCase();
} catch (NullPointerException nullPointerException) {
assertThrows(NullPointerException.class, () -> {
throw nullPointerException;
});
} catch (Exception exception) {
fail("Expected NullPointerException, but caught: " + exception.getClass().getSimpleName());
}
}
}
In the above example, we have made use of the assertThrows method from org.junit.jupiter.api.Assertions class of Junit 5.
For this example: The method asserts that execution of the supplied executable throws an exception of the expectedType (NullPointerException) and returns the exception. If there is no exception thrown by your code, or a different expectation other than NullPointerException is thrown assertThrows method will fail.
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!