JUnit: Failing Test on NullPointerException Example


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.



Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap