JUnit 5 assertNull and assertNotNull Example

In this article, we will learn about assertNull() and assertNotNull() static methods which are belongs to JUnit 5 org.junit.jupiter.api.Assertions Class. Note that in JUnit 5 all JUnit 4 assertion methods are moved to org.junit.jupiter.api.Assertions class.
There are many overloaded version of these two methods present in org.junit.jupiter.api.Assertions class.
Let me list out tools and technologies that I have used to develop JUnit 5 assertNull and assertNotNull Example.

Tools and Technologies Used

  1. Eclipse photon (only this eclipse version supports JUnit 5)
  2. Maven
  3. JUnit 5
  4. JDK 8 or later

assertNull() Method Example

import static org.junit.Assert.assertNull;

import org.junit.jupiter.api.Test;

public class JUnit5AssertNullExample {
 public static String[] concatenateStringArrays(final String[] array1, final String[] array2) {
  if (array1 == null || array1.length == 0) {
   return array2;
  }
  if (array2 == null || array2.length == 0) {
   return array1;
  }

  final String[] newArr = new String[array1.length + array2.length];
  System.arraycopy(array1, 0, newArr, 0, array1.length);
  System.arraycopy(array2, 0, newArr, array1.length, array2.length);
  return newArr;
 }

 @Test
 public void testConcatenateStringArrays() {
  assertNull(concatenateStringArrays(null, null));
 }
}

Output

assertNotNull() Method Example

import static org.junit.jupiter.api.Assertions.assertNotNull;

import java.util.Arrays;
import java.util.Collection;

import org.junit.jupiter.api.Test;

public class JUnit5AssertNotNullExample {
 public static String[] toStringArray(final Collection<?> collection) {
  if (collection == null) {
   return null;
  }
  return collection.toArray(new String[collection.size()]);
 }

 @Test
 public void toStringArrayTest() {
  final String[] strArray = toStringArray(Arrays.asList("a", "b", "c"));
  for (final String element : strArray) {
   assertNotNull(element);
  }
 }
}

Output

Comments