Hey guys in this post, we will discuss the Junit5 assertNull()
method with easy to understanding example
Read More:
- Check the Complete JUnit 5 Tutorial
- Check the Complete JavaServer Faces (JSF) Tutorial
- Check the Spring Boot JdbcTemplate Tutorials
- Check the Complete Spring Boot and Data JPA Tutorials
- Check the Complete Spring MVC Tutorials
- Check the Complete JSP Tutorials
- Check the Complete Spring Boot Tutorials [100+ Examples]
- Check the Complete Spring Boot and Thymeleaf Tutorial
- Check the Complete AWS Tutorial
- Check the Complete JavaServer Faces (JSF) Tutorial
- Check the Complete Spring Data JPA Tutorial
- Check the Complete Spring Security Tutorial
- Check the Javascript Projects for Beginners
Overview
JUnit5 provides the assertNull()
method, it asserts that the object is null. There are many overloaded assertNull()
methods available. Below is just a sample screenshot for your reference.
Example
Consider the following method for checking the null
value.
package in.bushansirgur.main;
public class MyUtils {
public Object checkNull(Object object) {
if (object != null) {
return object;
}
return null;
}
}
JUnit5 Success Test Case
Now we want to write a JUnit5 test case for the above method, we can use the assertNull()
method to assert that the object is null
package in.bushansirgur.main;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class MyUtilsTest {
@Test
void testNull() {
MyUtils myUtils = new MyUtils();
assertNull(myUtils.checkNull(null), () -> "It should be null");
}
}
When we run the test case, we should see a green bar indicating that the test case passed.
JUnit5 Failure Test Case
Now if anyone changes the implementation/logic then the test case should fail. Let’s change the method implementation with the following code –
package in.bushansirgur.main;
public class MyUtils {
public Object checkNull(Object object) {
if (object != null) {
return object;
}
return "";
}
}
Now when we run the test case, we should see a red bar indicating that the test case failed.
That’s it for this post, if you like this post, share this with your friends and colleagues or you can share this within your social media platform. Thanks, I will see you in our next post.