How to Use assertNotNull in JUnit for Null Checks
Use
assertNotNull in JUnit to check that an object is not null during a test. It takes the object as a parameter and fails the test if the object is null, helping ensure your code returns or creates valid objects.Syntax
The assertNotNull method is used to verify that an object is not null in a test. It has two common forms:
assertNotNull(Object actual)- Fails ifactualis null.assertNotNull(String message, Object actual)- Fails with a custommessageifactualis null.
This method helps confirm that your code produces or returns a valid object.
java
assertNotNull(actual); assertNotNull(message, actual);
Example
This example shows how to use assertNotNull in a JUnit 5 test to check that a method returns a non-null string.
java
import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; public class SampleTest { public String getGreeting() { return "Hello, World!"; } @Test public void testGetGreetingIsNotNull() { String greeting = getGreeting(); assertNotNull(greeting, "Greeting should not be null"); } }
Output
Test passed successfully with no failures.
Common Pitfalls
Common mistakes when using assertNotNull include:
- Passing a primitive type instead of an object (primitives cannot be null).
- Not providing a helpful failure message, which makes debugging harder.
- Using
assertNotNullwhen you actually want to check for equality or other conditions.
Always ensure the object you test can actually be null and that the assertion matches your test goal.
java
import static org.junit.jupiter.api.Assertions.assertNotNull; import org.junit.jupiter.api.Test; public class PitfallTest { @Test public void wrongUsage() { int number = 5; // This compiles but is meaningless because int is primitive and never null // assertNotNull(number); // Avoid this } @Test public void rightUsage() { String text = null; // This will fail the test with a clear message assertNotNull(text, "Text should not be null"); } }
Output
Test 'rightUsage' fails with message: Text should not be null
Quick Reference
Use this quick guide when working with assertNotNull:
| Usage | Description |
|---|---|
| assertNotNull(object) | Fails if object is null |
| assertNotNull(message, object) | Fails with message if object is null |
| Use with objects only | Primitives cannot be null, so avoid using assertNotNull on them |
| Provide clear messages | Helps identify why a test failed quickly |
Key Takeaways
Use assertNotNull to verify an object is not null in your tests.
Provide a custom failure message to make debugging easier.
Do not use assertNotNull on primitive types like int or boolean.
assertNotNull helps catch unexpected null values early in testing.
Combine assertNotNull with other assertions for thorough tests.