java - 如何检查 hamcrest 集合中某些项目的大小和存在

标签 java junit hamcrest

我正在使用 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/

相关文章:

java - 如何使用 Hamcrest 验证 map 大小

java - 如何在 spring mvc 中数据绑定(bind)列出选定的复选框

循环中的java junit测试

java - Mockito 谓词中的 "OR"匹配器问题

java - 使用 Mockito 对 SharedPreferences 包装器进行单元测试

maven - Junit 报告为 PDF,最好使用 Maven

java - 为什么 IsIterableContainingInOrder Hamcrest 匹配器无法处理数组?

java - 在 Codename One 应用程序中使用 SQLite

java - 在android项目中放置并运行apk文件

java - 需要按钮留在我的对话框底部