0
0
JunitHow-ToBeginner ยท 3 min read

How to Use assertNull in JUnit for Null Checks

In JUnit, use assertNull(object) to check if an object is null. If the object is not null, the test will fail, helping you verify expected null values in your code.
๐Ÿ“

Syntax

The assertNull method checks if the given object is null. It has two common forms:

  • assertNull(Object actual): Fails if actual is not null.
  • assertNull(String message, Object actual): Same as above but shows message if the test fails.

This method is part of the org.junit.jupiter.api.Assertions class in JUnit 5.

java
assertNull(Object actual)
assertNull(String message, Object actual)
๐Ÿ’ป

Example

This example shows how to use assertNull to test that a method returns null when expected.

java
import static org.junit.jupiter.api.Assertions.assertNull;
import org.junit.jupiter.api.Test;

class UserService {
    String findUserById(int id) {
        // Simulate no user found
        return null;
    }
}

public class UserServiceTest {
    @Test
    void testFindUserByIdReturnsNull() {
        UserService service = new UserService();
        String user = service.findUserById(10);
        assertNull(user, "User should be null when not found");
    }
}
Output
Test passed successfully with no failures.
โš ๏ธ

Common Pitfalls

Common mistakes when using assertNull include:

  • Passing a non-null object, causing the test to fail unexpectedly.
  • Confusing assertNull with assertNotNull.
  • Not providing a helpful failure message, making debugging harder.

Always verify the object you test can actually be null in the scenario.

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

public class ExampleTest {
    @Test
    void wrongUsage() {
        String text = "hello";
        // This will fail because text is not null
        assertNull(text); // Wrong
    }

    @Test
    void correctUsage() {
        String text = null;
        assertNull(text, "Expected null value"); // Correct
    }
}
Output
Test 'wrongUsage' failed: expected null but was "hello" Test 'correctUsage' passed.
๐Ÿ“Š

Quick Reference

MethodDescription
assertNull(Object actual)Fails if actual is not null.
assertNull(String message, Object actual)Fails with message if actual is not null.
โœ…

Key Takeaways

Use assertNull to verify an object is null in your tests.
Provide a failure message to make test failures easier to understand.
Do not confuse assertNull with assertNotNull.
assertNull fails the test if the object is not null.
assertNull is part of JUnit 5 Assertions class.