0
0
JUnittesting~5 mins

assertNull and assertNotNull in JUnit

Choose your learning style9 modes available
Introduction

We use assertNull to check if something is empty or missing. We use assertNotNull to check if something exists or is present.

When you want to make sure a method returns nothing (null) after some action.
When you want to confirm that an object or value is created and not empty.
When testing if a database query returns no result (null) or some data (not null).
When checking if a user input was not provided (null) or was given (not null).
When verifying that a service response is present or missing.
Syntax
JUnit
assertNull(Object actual)
assertNotNull(Object actual)

Both methods come from the org.junit.jupiter.api.Assertions class in JUnit 5.

If the condition fails, the test will stop and show an error.

Examples
This checks that the user's middle name is missing (null).
JUnit
assertNull(user.getMiddleName());
This checks that the database connection is established (not null).
JUnit
assertNotNull(databaseConnection);
This checks that the error message is null and shows a custom message if it is not.
JUnit
assertNull(response.getErrorMessage(), "Error message should be null");
This checks that the API key is present and shows a message if missing.
JUnit
assertNotNull(config.getApiKey(), "API key must be set");
Sample Program

This test class checks if the user's middle name is null or not null using assertNull and assertNotNull.

JUnit
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public class UserTest {

    static class User {
        private String middleName;
        public String getMiddleName() { return middleName; }
        public void setMiddleName(String middleName) { this.middleName = middleName; }
    }

    @Test
    void testMiddleNameIsNull() {
        User user = new User();
        assertNull(user.getMiddleName());
    }

    @Test
    void testMiddleNameIsNotNull() {
        User user = new User();
        user.setMiddleName("Lee");
        assertNotNull(user.getMiddleName());
    }
}
OutputSuccess
Important Notes

Use assertNull when you expect no value (null).

Use assertNotNull when you expect a value to be present.

Adding a message helps understand test failures quickly.

Summary

assertNull checks if a value is null (empty).

assertNotNull checks if a value is not null (exists).

Both help confirm expected presence or absence of data in tests.