断言JUnit中的列表不为空

Ich*_*aki 34 junit junit4

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

assertThat(result.isEmpty(), is(false));
Run Code Online (Sandbox Code Playgroud)

这给了我这个错误:

对于类型MaintenanceDaoImplTest,方法是(boolean)未定义

如何在不使用的情况下这样做Hamcrest.

JB *_*zet 66

你可以简单地使用

assertFalse(result.isEmpty());
Run Code Online (Sandbox Code Playgroud)

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

import static org.hamcrest.CoreMatchers.is;
Run Code Online (Sandbox Code Playgroud)

  • 现在更好的方法是`assertThat(myList,is(not(empty())));` (5认同)

Laz*_*ana 15

这读得非常好,并使用Hamcrest.正是你所要求的;)当代码读起来像评论时总是很好.

assertThat(myList, is(empty()));
assertThat(myList, is(not(empty())));
Run Code Online (Sandbox Code Playgroud)

你可以添加is静态导入到你的IDE,因为我知道eclipse和IntelliJ正在努力建议它甚至当它在类路径上时.


的IntelliJ

Settings -> Code Style -> Java -> Imports 
Run Code Online (Sandbox Code Playgroud)

日食

Prefs -> Java -> Editor -> Content Assist -> Favourites 
Run Code Online (Sandbox Code Playgroud)

进口本身就是 import static org.hamcrest.CoreMatchers.is;

  • 那 `empty()` 怎么样,它没有为我解决,它也是用户定义的还是需要静态导入? (7认同)
  • @basheer:导入静态org.hamcrest.Matchers.empty; (7认同)

小智 5

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

Assertions.assertNotEquals(Collections.EMPTY_LIST, yourList);
Run Code Online (Sandbox Code Playgroud)