3

我正在尝试将整数列表与 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))));

谢谢

4

3 回答 3

7

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

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

如果是这样:

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

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

assertThat(numbers, hasSize(5));
于 2012-12-14T12:20:36.037 回答
2

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

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))
于 2012-12-15T07:58:54.680 回答
1

只需使用

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

或者

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

顺序在这里并不重要。

于 2012-12-14T12:20:45.033 回答