断言 JUnit 中的列表不为空

问题描述 投票:0回答:8

我想断言 JUnit 4 中的列表不为空,当我用 google 搜索它时,我发现了这篇文章:使用 Hamcrest 检查 Hamcrest 中的列表不为空。

assertThat(result.isEmpty(), is(false));

这给了我这个错误:

该类型的方法 is(boolean) 未定义 维护DaoImplTest

如何在不使用

Hamcrest
的情况下做到这一点。

junit junit4
8个回答
126
投票

您可以简单地使用

assertFalse(result.isEmpty());

关于您的问题,这只是由于您忘记从 Hamcrest 静态导入

is()
方法所致;

import static org.hamcrest.CoreMatchers.is;

42
投票

这读起来非常好并且使用 Hamcrest。正是您所要求的;) 当代码读起来像注释时总是很好。

assertThat(myList, is(empty()));
assertThat(myList, is(not(empty())));

您可以将

is
作为静态导入添加到 IDE 中,因为我知道 Eclipse 和 IntelliJ 正在努力建议它,即使它位于类路径上。


IntelliJ

Settings -> Code Style -> Java -> Imports 

日食

Prefs -> Java -> Editor -> Content Assist -> Favourites 

导入本身是

import static org.hamcrest.CoreMatchers.is;


5
投票

您可以检查您的列表是否不等于空列表(

Collections.EMPTY_LIST
),尝试以下操作:

Assertions.assertNotEquals(Collections.EMPTY_LIST, yourList);

1
投票

我喜欢用

Assert.assertEquals(List.of(), result)

这样,如果列表不为空,您会收到一条非常好的错误消息。例如

java.lang.AssertionError: 
Expected :[]
Actual   :[something unexpected]

1
投票

assertEquals(Collections.Empty_List,Collections.emptyList())

试试这个。


0
投票

在junit5中我们可以像下面这样简单易用地使用它。 assertThat(结果).isEmpty();


-2
投票

我也在寻找类似的东西,但最简单的解决方法可能是

Assert.AreEqual(result.Count, 0);

当收藏没有记录时。


-2
投票

您可以将“is”更改为“equalTo”: assertThat(result.isEmpty(), equalTo(false));

© www.soinside.com 2019 - 2024. All rights reserved.