1. 概述

在Java单元测试(尤其是使用JUnit框架时)中,我们经常需要验证变量是否为null或非null。Hamcrest作为流行的Matcher库,提供了灵活的测试断言方案。本文将快速介绍如何通过JUnit和Hamcrest实现null检查。

2. 使用Hamcrest的assertThat()

首先需在pom.xml添加依赖:

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest</artifactId>
    <version>2.2</version>
    <scope>test</scope>
</dependency>

Hamcrest的assertThat()方法和Matcher支持灵活断言。null检查的核心工具在org.hamcrest.core.IsNull类中,提供两个关键静态方法:

  • ✅ *nullValue()*:匹配null值
  • ✅ *notNullValue()*:匹配非null值

更便捷的是,org.hamcrest.Matchers类也封装了这些方法(实际调用IsNull类)。推荐静态导入简化代码:

import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.nullValue;

使用示例:

String theNull = null;
assertThat(theNull, nullValue());
 
String theNotNull = "I am a good String";
assertThat(theNotNull, notNullValue());

⚠️ 替代方案:非null检查也可用组合Matcher实现:

assertThat(theNotNull, not(nullValue()));

*not()*方法来自org.hamcrest.core.IsNot,用于逻辑取反。

3. 使用JUnit的null断言

Hamcrest虽强大,但JUnit原生方法更简单粗暴:

  • ✅ *assertNull()*:验证变量为null
  • ✅ *assertNotNull()*:验证变量非null
String theNull = null;
assertNull(theNull); 
 
String theNotNull = "I am a good String";
assertNotNull(theNotNull);

对有经验的开发者来说,这些基础方法无需过多解释——直接用就完事了。

4. 总结

本文对比了两种null检查方案:

  1. Hamcrest方案:通过*nullValue()notNullValue()*实现语义化断言,代码可读性更强
  2. JUnit原生方案:使用*assertNull()assertNotNull()*,简单直接

选择建议:

  • 需要复杂断言组合时选Hamcrest
  • 简单null检查用JUnit原生方法更高效

完整示例代码见GitHub仓库


原始标题:Check if a Variable Is Null Using Hamcrest | Baeldung