在JUnit中Assert列表不为空

vshtjzan  于 11个月前  发布在  其他
关注(0)|答案(8)|浏览(132)

我想AssertJUnit 4中的列表不是空的,当我在谷歌上搜索它时,我发现了这篇文章:Checking that a List is not empty in Hamcrest,它使用了Hamcrest。

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

字符串
这给了我这个错误:
对于MaintenanceDaoImplTest类型,方法is(boolean)未定义
如果不使用Hamcrest,我该怎么做?

ajsxfq5m

ajsxfq5m1#

你可以简单地使用

assertFalse(result.isEmpty());

字符串
关于您的问题,它只是由于您忘记从Hamcrest静态导入is()方法而引起的;

import static org.hamcrest.CoreMatchers.is;

j2datikz

j2datikz2#

这段代码读起来很好,使用了Hamcrest。正是你所要求的;)当代码读起来像注解时,总是很好。

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

字符串

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

IntelliJ

Settings -> Code Style -> Java -> Imports

Eclipse

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


导入本身是import static org.hamcrest.CoreMatchers.is;

qxsslcnc

qxsslcnc3#

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

Assertions.assertNotEquals(Collections.EMPTY_LIST, yourList);

字符串

ipakzgxi

ipakzgxi4#

我喜欢用

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

字符串
这样,如果列表不是空的,你会得到一个很好的错误消息。

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

dhxwm5r4

dhxwm5r45#

如果您是一个空的列表,请使用下面的函数:
试试这个.

e0bqpujr

e0bqpujr6#

在6月5日,我们可以使用下面的简单和容易。

assertThat(result).isEmpty();

字符串

dhxwm5r4

dhxwm5r47#

我也在寻找类似的东西,但最简单的工作可以是

Assert.AreEqual(result.Count, 0);

字符串
当集合没有记录时。

92vpleto

92vpleto8#

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

相关问题