我有一个整数列表(current),我想检查这个列表是否包含list expected中的所有元素,而不包含list notExpected中的一个元素,因此代码如下所示:
List<Integer> expected= new ArrayList<Integer>();
expected.add(1);
expected.add(2);
List<Integer> notExpected = new ArrayList<Integer>();
notExpected.add(3);
notExpected.add(4);
List<Integer> current = new ArrayList<Integer>();
current.add(1);
current.add(2);
assertThat(current, not(hasItems(notExpected.toArray(new Integer[expected.size()]))));
assertThat(current, (hasItems(expected.toArray(new Integer[expected.size()]))));再见,再见,真好。但当我添加
current.add(3);测试也是绿色的。我是不是误用了汉姆克雷斯特火柴盒?顺便说一句。
for (Integer i : notExpected)
assertThat(current, not(hasItem(i)));给了我正确的答案,但我认为我可以很容易地使用hamcrest matcher来解决这个问题。我使用的是junit 4.11和hamcrest 1.3
发布于 2013-02-18 17:52:44
只有当来自hasItems(notExpected...)的所有元素都在current中时,notExpected才会与current匹配。所以有了这条线
assertThat(current, not(hasItems(notExpected...)));您断言current不包含来自notExpected的所有元素。
断言current不包含任何来自notExpected的元素的一种解决方案
assertThat(current, everyItem(not(isIn(notExpected))));然后,您甚至不必将列表转换为数组。这个变体可能更具可读性,但需要转换为数组:
assertThat(current, everyItem(not(isOneOf(notExpected...))));请注意,这些匹配器不是来自hamcrest-core中的CoreMatchers,因此您需要添加对hamcrest-library的依赖。
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
</dependency>https://stackoverflow.com/questions/14932363
复制相似问题