Table of Contents
Junit 5’s org.junit.jupiter.Assertions class provides different static assertions method to write test cases.
Assertions.assertNull() checks that object is null. In case, object is not null, it will through AssertError.
public static void assertNull(Object actual, String message)
public static void assertNull(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 |
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 AssertNullTest { AssertNullTest ant; public String getCapital(String country){ Map<String,String> countryCapitalMap = new HashMap<String,String>(); countryCapitalMap.put("Italy", "Rome"); countryCapitalMap.put("Japan", "Tokyo"); countryCapitalMap.put("Zimbabwe", "Harare"); countryCapitalMap.put("Belgiaum", "Brussels"); return countryCapitalMap.get(country); } @BeforeEach public void beforeEachTest() { ant = new AssertNullTest(); } /* * Examples for each overloaded methods of assertNull */ //public static void assertNull(Object actual) @Test public void testIndia(){ String capitalIndia=ant.getCapital("India"); Assertions.assertNull(capitalIndia); } //public static void assertNull(Object actual, String message) @Test public void testUSA(){ String capitalUSA=ant.getCapital("USA"); // You can pass message as well Assertions.assertNull(capitalUSA,"Capital should be null"); } //public static void assertNull(Object actual, Supplier messageSupplier) @Test public void testJapan(){ String capitalJapan=ant.getCapital("Japan"); Assertions.assertNull(capitalJapan,() -> "Capital should be null"); } } |
When you run above testcase, you will get below output:
Let’s understand output of each testcase:
testIndia – Pass
As countryCapitalMap does not contain key “India”, assertNull will return true and this testcase will pass.
testUSA – Pass
As countryCapitalMap does not contain key “USA”, assertNull will return true and this testcase will pass.
testJapan – Fail
As countryCapitalMap contains key “Japan”, assertNull will return false and this testcase will fail.
That’s all about Assertions.assertNull() method.