Core Java

Check if a Variable Is Null Using Hamcrest

In unit testing, verifying that a variable is null is a common task. Hamcrest, a popular framework for writing matcher objects, provides a clean and readable way to assert conditions in tests. Let us delve to check if a variable is null using Hamcrest’s assertThat(), and also discuss JUnit’s null and non-null assertions.

1. Introduction

Hamcrest is a popular framework used for writing matcher objects, allowing for more readable and expressive test code. At the heart of Hamcrest lies the assertThat() method, which is a powerful and versatile tool for making assertions in tests. The assertThat() method takes two parameters: the actual value to be tested and a matcher that defines the expected condition. This method allows for more fluent and natural language expressions in tests, making it easier to understand and maintain the test code. By using a variety of matchers, such as is(), equalTo(), and nullValue(), developers can create precise and descriptive assertions, thereby enhancing the readability and expressiveness of their unit tests.

1.1 Comparison between Hamcrest and Junit

AspectHamcrestJUnit
PurposeProvides a library of matcher objects for creating readable and flexible test assertions.A testing framework for Java that provides various assertions and test annotations to write and run tests.
Main Assertion MethodassertThat()assertEquals(), assertTrue(), assertFalse(), assertNull(), assertNotNull()
FlexibilityHighly flexible with a wide range of matchers allowing for expressive and complex assertions.Provides basic assertions that are straightforward but less expressive compared to Hamcrest matchers.
ReadabilityFocuses on readability and fluency of assertions, making test code easier to read and understand.Assertions are less fluent and can be more verbose, but are simple and to the point.
IntegrationCan be easily integrated with JUnit and other testing frameworks to enhance assertion capabilities.Works as a standalone testing framework but can integrate with other libraries for additional functionalities.
Common UsageUsed for creating custom and detailed assertions in unit tests.Used for writing and running tests with basic assertions and test lifecycle management.

2. Using Hamcrest’s assertThat()

To check if a variable is null, you can use the is matcher in conjunction with nullValue().

2.1 Code Example

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.nullValue;

public class HamcrestNullTest {
  public static void main(String[] args) {
    String variable = null;
    assertThat(variable, nullValue());
  }
}

In the code above:

  • assertThat(variable, nullValue()) checks if variable is null.
  • nullValue() is a matcher that verifies the value is null.

The test passes silently if the variable is null. If the variable is not null, the test fails, and an AssertionError is thrown.

java.lang.AssertionError: 
Expected: is 
     but: was 
    at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:18)
    at com.example.HamcrestNullTest.testVariableIsNull(HamcrestNullTest.java:10)

3. Using JUnit’s null and Non-Null Assertions

JUnit provides built-in assertions for checking null and non-null values. These assertions are easy to use.

3.1 Code Example

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class JUnitNullTest {
  @Test
  public void testVariableIsNull() {
    String variable = null;
    assertNull(variable);
  }

  @Test
  public void testVariableIsNotNull() {
    String variable = "Not Null";
    assertNotNull(variable);
  }
}

In the code above:

  • assertNull(variable) checks if variable is null and passes if it is.
  • assertNotNull(variable) checks if variable is not null and passes if it is not null.

The test passes silently if the conditions are met. If the conditions are not met, an AssertionError is thrown.

org.junit.ComparisonFailure: 
Expected :null
Actual   :SomeValue
    at org.junit.Assert.assertNull(Assert.java:253)
    at com.example.JUnitNullTest.testVariableIsNull(JUnitNullTest.java:12)

4. Conclusion

Checking for null values is a common requirement in unit testing. Hamcrest’s assertThat() method with nullValue() matcher provides a readable and expressive way to assert null values. Additionally, JUnit offers straightforward assertions with assertNull and assertNotNull to verify null and non-null conditions. Using these tools effectively can lead to more readable and maintainable test code.

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button