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.
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.
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"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts for testFindUserByIdReturnsNull | JUnit test runner initialized | — | PASS |
| 2 | Calls findUserById with id=0 | Method returns null | — | PASS |
| 3 | assertNull checks that result is null | Result is null | assertNull(result) | PASS |
| 4 | Test ends for testFindUserByIdReturnsNull | Test passed | — | PASS |
| 5 | Test starts for testFindUserByIdReturnsNotNull | JUnit test runner initialized | — | PASS |
| 6 | Calls findUserById with id=1 | Method returns "User1" | — | PASS |
| 7 | assertNotNull checks that result is not null | Result is "User1" | assertNotNull(result) | PASS |
| 8 | Test ends for testFindUserByIdReturnsNotNull | Test passed | — | PASS |
assertNull(object) verify in a test?assertNull checks if the given object is null, meaning it has no value assigned.user is NOT null in JUnit?assertNotNull as a method with parentheses and the object as argument.String name = null; assertNull(name); name = "Alice"; assertNotNull(name);
name is null, so assertNull(name) passes.name is assigned "Alice", which is not null, so assertNotNull(name) passes.Object obj = new Object(); assertNull(obj);
obj is assigned a new Object instance, so it is not null.assertNull(obj) expects null, but obj is not null, so the assertion fails.getUserEmail() that returns a String email or null if no email is set. Which JUnit assertions correctly test that the email is present and not empty?assertNotNull(email) to ensure email is not null (exists).assertTrue(!email.isEmpty()) to confirm email has characters.Pass the test and this pattern moves unknown