To test null and non-null values in JUnit, use these assertions:
assertNull(value)— passes if the value isnullassertNotNull(value)— passes if the value is notnull
In JUnit 5, these methods are available from org.junit.jupiter.api.Assertions.
Basic Example
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class NullCheckTest {
@Test
void valueShouldBeNull() {
String name = null;
assertNull(name);
}
@Test
void valueShouldNotBeNull() {
String name = "John";
assertNotNull(name);
}
}
Using Assertion Messages
You can add a message to make test failures easier to understand.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class NullCheckTest {
@Test
void valueShouldBeNull() {
String result = null;
assertNull(result, "The result should be null");
}
@Test
void valueShouldNotBeNull() {
String result = "Hello JUnit";
assertNotNull(result, "The result should not be null");
}
}
Testing a Method That May Return Null
Suppose you have a method that returns a username:
class UserService {
String findUsernameById(int id) {
if (id == 1) {
return "Alice";
}
return null;
}
}
You can test both cases like this:
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
class UserServiceTest {
private final UserService userService = new UserService();
@Test
void findUsernameByIdReturnsNameWhenUserExists() {
String username = userService.findUsernameById(1);
assertNotNull(username);
assertEquals("Alice", username);
}
@Test
void findUsernameByIdReturnsNullWhenUserDoesNotExist() {
String username = userService.findUsernameById(99);
assertNull(username);
}
}
Testing Null Arguments
If your code should reject null values, use assertThrows() to check that an exception is thrown.
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
class PersonTest {
@Test
void constructorThrowsExceptionWhenNameIsNull() {
NullPointerException exception = assertThrows(
NullPointerException.class,
() -> new Person(null)
);
assertEquals("Name cannot be null", exception.getMessage());
}
}
class Person {
private final String name;
Person(String name) {
if (name == null) {
throw new NullPointerException("Name cannot be null");
}
this.name = name;
}
}
Summary
Use:
assertNull(value);
assertNotNull(value);
For null-related exceptions, use:
assertThrows(NullPointerException.class, () -> {
// code that should throw NullPointerException
});
These assertions are the standard way to test null and non-null values in JUnit 5.
