Junit assertNotNull example

Junit 5’s org.junit.jupiter.Assertions class provides different static assertions method to write test cases.

Please note that you need to use JUnit’s org.junit.Assert class in case of JUnit 4 or JUnit 3 to assert using assertNotNull method.

Assertions.assertNotNull() checks if object is not null. In case, object is null, it will through AssertError.

public static void assertNotNull(Object actual)
public static void assertNotNull(Object actual, String message)
public static void assertNotNull(Object actual, Supplier messageSupplier)

Here is simple example

When you run above testcase, you will get below output:
AssertNotNullTestOutput

Let’s understand output of each testcase:


testIndia – Pass

As countryCapitalMap contains key “India”, AssertNotNull will return true and this testcase will pass.


testUSA – Fail

As countryCapitalMap does not contain key “USA”, AssertNotNull will return true and this testcase will fail.


testBhutan – Pass

As countryCapitalMap contains key “Bhutan”, AssertNotNull will return true and this testcase will pass.


That’s all about Assertions.assertNotNull()

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *