断言集合不包含项目

har*_*are 64 java hamcrest

使用用于Java的hamcrest库,可以很好地读取相反的方法:

assertThat(someCollection, hasItem(someItem))
Run Code Online (Sandbox Code Playgroud)

我想确保someCollection不包含项目someItem

dee*_*see 112

否定hasItem断言

assertThat(someCollection, not(hasItem(someItem)))
Run Code Online (Sandbox Code Playgroud)

  • 一旦我导入了包IsNot(`import static org.hamcrest.core.IsNot.not`),它运行良好. (9认同)
  • @harschware - 来自[基础教程](http://code.google.com/p/hamcrest/wiki/Tutorial),`import static org.hamcrest.MatcherAssert.assertThat;`和`import static org.hamcrest.Matchers .*;` (6认同)
  • 在 hamcrest 版本 1.3-assertThat(someCollection, not(hasItem(someItem))) 不起作用,所以我使用了assertThat(someCollection, not(contains(someItem))) (3认同)

小智 5

如果您需要声明一个数组,则使用相同的逻辑 not(hasItemInArray())

final String[] availableIds = {"123", "321"};
final String userId = "333";

softAssert.assertThat("Id not found", availableIds, not(hasItemInArray(userId)));
softAssert.assertAll();
Run Code Online (Sandbox Code Playgroud)