0
0
JUnittesting~15 mins

assertNull and assertNotNull in JUnit - Build an Automation Script

Choose your learning style9 modes available
Verify assertNull and assertNotNull behavior in JUnit
Preconditions (2)
Step 1: Call a method that returns null
Step 2: Use assertNull to verify the returned value is null
Step 3: Call a method that returns a non-null object
Step 4: Use assertNotNull to verify the returned value is not null
✅ Expected Result: assertNull passes when the value is null, assertNotNull passes when the value is not null
Automation Requirements - JUnit 5
Assertions Needed:
assertNull to check null values
assertNotNull to check non-null values
Best Practices:
Use descriptive test method names
Use @Test annotation for test methods
Keep tests independent and focused
Use clear assertion messages
Automated Solution
JUnit
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import org.junit.jupiter.api.Test;

public class NullCheckTest {

    // Method that returns null
    public String getNullValue() {
        return null;
    }

    // Method that returns a non-null string
    public String getNonNullValue() {
        return "Hello";
    }

    @Test
    public void testAssertNull() {
        String result = getNullValue();
        assertNull(result, "Expected result to be null");
    }

    @Test
    public void testAssertNotNull() {
        String result = getNonNullValue();
        assertNotNull(result, "Expected result to be not null");
    }
}

This test class NullCheckTest has two methods: one returns null, the other returns a string.

The testAssertNull method calls the method returning null and uses assertNull to check the value is null. The assertion message helps understand the failure if it happens.

The testAssertNotNull method calls the method returning a string and uses assertNotNull to check the value is not null.

Each test is independent and clearly named to show what it verifies.

Common Mistakes - 4 Pitfalls
Using assertNull on a non-null value
Not providing assertion messages
Testing multiple unrelated things in one test method
Forgetting @Test annotation on test methods
Bonus Challenge

Now add data-driven testing with 3 different inputs: null, empty string, and a non-empty string

Show Hint