0
0
JUnittesting~10 mins

assertNull and assertNotNull in JUnit - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test checks if a method returns null or a non-null object as expected. It uses assertNull to verify a null result and assertNotNull to verify a non-null result.

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

class UserService {
    String findUserById(int id) {
        if (id == 0) return null;
        return "User" + id;
    }
}

public class UserServiceTest {
    UserService service = new UserService();

    @Test
    void testFindUserByIdReturnsNull() {
        String result = service.findUserById(0);
        assertNull(result, "Expected null when user ID is 0");
    }

    @Test
    void testFindUserByIdReturnsNotNull() {
        String result = service.findUserById(1);
        assertNotNull(result, "Expected non-null when user ID is 1");
    }
}
Execution Trace - 8 Steps
StepActionSystem StateAssertionResult
1Test starts for testFindUserByIdReturnsNullJUnit test runner initialized-PASS
2Calls findUserById with id=0Method returns null-PASS
3assertNull checks that result is nullResult is nullassertNull(result)PASS
4Test ends for testFindUserByIdReturnsNullTest passed-PASS
5Test starts for testFindUserByIdReturnsNotNullJUnit test runner initialized-PASS
6Calls findUserById with id=1Method returns "User1"-PASS
7assertNotNull checks that result is not nullResult is "User1"assertNotNull(result)PASS
8Test ends for testFindUserByIdReturnsNotNullTest passed-PASS
Failure Scenario
Failing Condition: assertNull fails if the method returns a non-null value when null is expected, or assertNotNull fails if the method returns null when a non-null value is expected.
Execution Trace Quiz - 3 Questions
Test your understanding
What does assertNull verify in the test?
AThat the returned value is null
BThat the returned value is not null
CThat the returned value equals "User1"
DThat the method throws an exception
Key Result
Use assertNull to verify that a method returns null when expected, and assertNotNull to verify it returns a valid object. This helps catch unexpected null or non-null values early.