JUnit5 assertNull() Example

Hey guys in this post, we will discuss the Junit5 assertNull() method with easy to understanding example




Read More:

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.

Screenshot-2022-07-25-at-11-22-59-PM

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.

Screenshot-2022-07-25-at-11-21-42-PM

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.

Screenshot-2022-07-25-at-11-22-11-PM

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.



About the author

Bushan Sirgur

Hey guys, I am Bushan Sirgur from Banglore, India. Currently, I am working as an Associate project in an IT company.

View all posts

Leave a Reply

Your email address will not be published. Required fields are marked *