0
0
JunitHow-ToBeginner ยท 3 min read

How to Use assertNotNull in JUnit for Null Checks

Use assertNotNull in JUnit to check that an object is not null during a test. It takes the object as a parameter and fails the test if the object is null, helping ensure your code returns or creates valid objects.
๐Ÿ“

Syntax

The assertNotNull method is used to verify that an object is not null in a test. It has two common forms:

  • assertNotNull(Object actual) - Fails if actual is null.
  • assertNotNull(String message, Object actual) - Fails with a custom message if actual is null.

This method helps confirm that your code produces or returns a valid object.

java
assertNotNull(actual);
assertNotNull(message, actual);
๐Ÿ’ป

Example

This example shows how to use assertNotNull in a JUnit 5 test to check that a method returns a non-null string.

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

import org.junit.jupiter.api.Test;

public class SampleTest {

    public String getGreeting() {
        return "Hello, World!";
    }

    @Test
    public void testGetGreetingIsNotNull() {
        String greeting = getGreeting();
        assertNotNull(greeting, "Greeting should not be null");
    }
}
Output
Test passed successfully with no failures.
โš ๏ธ

Common Pitfalls

Common mistakes when using assertNotNull include:

  • Passing a primitive type instead of an object (primitives cannot be null).
  • Not providing a helpful failure message, which makes debugging harder.
  • Using assertNotNull when you actually want to check for equality or other conditions.

Always ensure the object you test can actually be null and that the assertion matches your test goal.

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

import org.junit.jupiter.api.Test;

public class PitfallTest {

    @Test
    public void wrongUsage() {
        int number = 5;
        // This compiles but is meaningless because int is primitive and never null
        // assertNotNull(number); // Avoid this
    }

    @Test
    public void rightUsage() {
        String text = null;
        // This will fail the test with a clear message
        assertNotNull(text, "Text should not be null");
    }
}
Output
Test 'rightUsage' fails with message: Text should not be null
๐Ÿ“Š

Quick Reference

Use this quick guide when working with assertNotNull:

UsageDescription
assertNotNull(object)Fails if object is null
assertNotNull(message, object)Fails with message if object is null
Use with objects onlyPrimitives cannot be null, so avoid using assertNotNull on them
Provide clear messagesHelps identify why a test failed quickly
โœ…

Key Takeaways

Use assertNotNull to verify an object is not null in your tests.
Provide a custom failure message to make debugging easier.
Do not use assertNotNull on primitive types like int or boolean.
assertNotNull helps catch unexpected null values early in testing.
Combine assertNotNull with other assertions for thorough tests.