如何使用Hamcrest声明一个通用的整数列表?

时间:2012-12-14 12:13:09

标签: java testing junit matching hamcrest

我正在尝试将一个整数列表与Hamcrest匹配,在线查看了一些示例但是我得到了运行时异常。

有些人可以告诉我什么是正确的语法吗?

List<Integer> numbers = Arrays.asList( 1, 2, 3, 4, 5 );
assertThat((List<Object>) numbers, hasItem(hasProperty("value", is(1))));
assertThat((List<Object>) numbers, hasItem(hasProperty("value", is(2))));
assertThat((List<Object>) numbers, hasItem(hasProperty("value", is(3))));
assertThat((List<Object>) numbers, hasItem(hasProperty("value", is(4))));
assertThat((List<Object>) numbers, hasItem(hasProperty("value", is(5))));

谢谢

3 个答案:

答案 0 :(得分:6)

如果列表项的顺序无关紧要:

assertThat(numbers, hasItems(1, 2, 3, 4, 5));

若是:

assertThat(numbers, is(equalTo(Arrays.asList(1, 2, 3, 4, 5))));

如果集合不应包含其他元素,那么还要检查大小:

assertThat(numbers, hasSize(5));

答案 1 :(得分:1)

只需使用

assertThat(numbers, hasItem(1));
...

或者

assertThat(numbers, hasItems(1, 2, 3, 4, 5));

订单无关紧要。

答案 2 :(得分:1)

验证集合是否包含特定项目:

assertThat(numbers, hasItem(3));

验证该集合包含多个项目:

assertThat(numbers, hasItems(3, 4));

验证集合中是否包含确切的特定项目:

assertThat(numbers, contains(1, 2, 3, 4, 5))

要验证集合中是否包含特定项目,请不要担心订单:

assertThat(numbers, containsInAnyOrder(5, 4, 3, 1, 2))