在junit中判断集合为空应使用 assertthat(collection, isempty()),它能同时处理空集合和null值。与手动检查不同,isempty() 匹配器内部已包含对null的安全判断,若集合为null则断言失败并提示具体原因,而 nullvalue() 仅用于验证对象是否为null,不检查集合内容。

如何正确区分空集合与null引用
要区分空集合和null,需分别使用 isEmpty() 和 nullValue() 两个不同的Hamcrest匹配器。当集合变量指向一个实际存在的空列表时,isEmpty() 会通过,而 nullValue() 会失败;反之,若变量为null,则 nullValue() 通过,isEmpty() 失败。这种区分有助于在测试中明确是“没有数据”还是“未初始化”。

import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class CollectionCheckTest {
@Test
public void testEmptyCollection() {
var list = List.of();
assertThat(list, is(empty()));
assertThat(list, not(nullValue()));
}
@Test
public void testNullCollection() {
var list = null;
assertThat(list, is(nullValue()));
// 以下断言会失败,因为isEmpty()在null时会抛出异常或标记为不匹配
// assertThat(list, is(empty()));
}
}
为什么推荐使用isEmpty()而非size()==0
使用 isEmpty() 比比较 size() == 0 更语义化且安全。前者直接表达“集合应为空”的意图,后者涉及方法调用和数值比较。更重要的是,isEmpty() 是Hamcrest标准匹配器,能提供更清晰的失败信息。若集合为null,size() 会抛出 NullPointerException,而 isEmpty() 会优雅地标记为不匹配,便于调试。

import org.junit.jupiter.api.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class SizeVsIsEmptyTest {
@Test
public void testSizeZero() {
var list = List.of();
assertThat(list.size(), is(0));
}
@Test(expected = NullPointerException.class)
public void testNullSize() {
var list = null;
assertThat(list.size(), is(0)); // 抛出NPE
}
}
基于List.of()返回的空集合的具体行为
对于 List.of() 返回的空集合,它是一个不可变的非null实例。因此,isEmpty() 返回true,size() 返回0,且它不是null。这与 new ArrayList() 类似,但 List.of() 保证不可变性。在测试中,可直接用 is(empty()) 验证其状态,无需担心null指针问题。











