Verify assertNull and assertNotNull behavior in JUnit
Preconditions (2)
✅ Expected Result: assertNull passes when the value is null, assertNotNull passes when the value is not null
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.
Now add data-driven testing with 3 different inputs: null, empty string, and a non-empty string
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