关于junit4:声明JUnit中的列表不为空

assert that a list is not empty in JUnit

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

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

这给了我这个错误:

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

不使用Hamcrest怎么办?


您可以简单地使用

1
assertFalse(result.isEmpty());

关于您的问题,仅是由于您忘记从Hamcrest静态导入is()方法而导致的;

1
import static org.hamcrest.CoreMatchers.is;


这很不错,并使用Hamcrest。正是您要的;)
当代码读起来像注释时,总是很好。

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

您可以将is作为静态导入添加到您的IDE中,因为我知道eclipse和IntelliJ甚至在类路径上也很难建议它。

IntelliJ

1
Settings -> Code Style -> Java -> Imports

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

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


您可以检查列表是否不等于空列表(Collections.EMPTY_LIST),请尝试以下操作:

1
Assertions.assertNotEquals(Collections.EMPTY_LIST, yourList);

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

尝试一下。


我喜欢使用

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

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

1
2
3
java.lang.AssertionError:
Expected :[]
Actual   :[something unexpected]

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


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

1
Assert.AreEqual(result.Count, 0);

当集合没有记录时。