我正在使用 Hamcrest 1.3 并尝试以更紧凑的方式实现以下目标。
考虑以下测试用例:
@Test
public void testCase() throws Exception {
Collection<String> strings = Arrays.asList(
"string one",
"string two",
"string three"
);
// variant 1:
assertThat(strings, hasSize(greaterThan(2)));
assertThat(strings, hasItem(is("string two")));
// variant 2:
assertThat(strings, allOf(
hasSize(greaterThan(2)),
hasItem(is("string two"))
));
}
这里的目标是检查集合的大小和要包含的一些特定项目。
如果第一个变化是可能的并被接受,那么做起来并不总是那么容易,因为集合本身可能是一些其他操作的结果,因此使用 allOf
操作对其进行所有操作更有意义.这是在上面的第二个变体中完成的。
但是包含第二个变体的代码将导致以下编译时错误:
error: no suitable method found for allOf(Matcher<Collection<? extends Object>>,Matcher<Iterable<? extends String>>)
实际上是否有任何特定的方法可以使用单次操作(例如 allOf
)来测试 Hamcrest 中集合的大小和项目?
最佳答案
我认为编译器无法理清泛型。以下对我有用(JDK 8u102):
assertThat(strings, Matchers.<Collection<String>> allOf(
hasSize(greaterThan(2)),
hasItem(is("string two"))
));
关于java - 如何检查 hamcrest 集合中某些项目的大小和存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40176940/