Table of Contents
Junit 5’s org.junit.jupiter.Assertions class provides different static assertions method to write test cases.
Assertions.assertNotNull() checks if object is not null. In case, object is null, it will through AssertError.
public static void assertNotNull(Object actual, String message)
public static void assertNotNull(Object actual, Supplier messageSupplier)
Here is simple example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
package org.arpit.java2blog; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; public class AssertNotNullTest { AssertNotNullTest annt; public String getCapital(String country){ Map<String,String> countryCapitalMap = new HashMap<String,String>(); countryCapitalMap.put("India", "Delhi"); countryCapitalMap.put("Nepal", "Kathmandu"); countryCapitalMap.put("China", "Beijing"); countryCapitalMap.put("Bhutan", "Thimphu"); return countryCapitalMap.get(country); } @BeforeEach public void beforeEachTest() { annt = new AssertNotNullTest(); } /* * Examples for each overloaded methods of assertNotNull */ //public static void assertNotNull(Object actual) @Test public void testIndia(){ String capitalIndia=annt.getCapital("India"); Assertions.assertNotNull(capitalIndia); } //public static void assertNotNull(Object actual, String message) @Test public void testUSA(){ String capitalUSA=annt.getCapital("USA"); // You can pass message as well Assertions.assertNotNull(capitalUSA,"Capital should not be null"); } //public static void assertNotNull(Object actual, Supplier messageSupplier) @Test public void testBhutan(){ String capitalUSA=annt.getCapital("Bhutan"); // You can pass message as well Assertions.assertNotNull(capitalUSA,() -> "Capital should not be null"); } } |
When you run above testcase, you will get below output:
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()