断言 JUnit 中的列表不为空

assert that a list is not empty in JUnit

我想断言 JUnit 4 中的列表不为空,当我用谷歌搜索时,我发现了这个 post : Checking that a List is not empty in Hamcrest 正在使用 Hamcrest。

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

这给了我这个错误:

The method is(boolean) is undefined for the type MaintenanceDaoImplTest

如果不使用 Hamcrest 我怎么能做到这一点。

您可以简单地使用

assertFalse(result.isEmpty());

关于你的问题,只是因为你忘记静态导入Hamcrest的is()方法;

import static org.hamcrest.CoreMatchers.is;

这读起来很不错,而且使用了 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;

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

Assert.AreEqual(result.Count, 0);

当collection没有记录时

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

我喜欢用

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

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

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

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

试试这个。

您可以检查您的列表是否不等于空列表 (Collections.EMPTY_LIST),试试这个:

Assertions.assertNotEquals(Collections.EMPTY_LIST, yourList);