"找不到合适的方法"当使用hasItem Hamcrest Matcher时

时间:2016-12-13 18:31:07

标签: java hamcrest

当我运行以下jUnit测试时:

@Test
public void test(){
    List<Map<String,String>> data=new ArrayList<>();
    Map<String,String> map=new HashMap<>();
    map.put("x","y");
    data.add(map);

    assertThat(data, hasItem(hasKey("x")));
}

我明白了:

Error:(239, 9) java: no suitable method found for assertThat(java.util.List>,org.hamcrest.Matcher>>)
    method org.junit.Assert.assertThat(java.lang.String,T,org.hamcrest.Matcher) is not applicable
      (cannot infer type-variable(s) T
        (actual and formal argument lists differ in length))
    method org.junit.Assert.assertThat(T,org.hamcrest.Matcher) is not applicable
      (inferred type does not conform to upper bound(s)
        inferred: java.util.List>
        upper bound(s): java.lang.Iterable>,java.lang.Object)

看起来仿制药中的某些东西正在崩溃。它是什么?

2 个答案:

答案 0 :(得分:0)

javac不知道如何推断某些方法的泛型类型。

assertThat期望该类型的值和Matcher。你必须明确

Assert.assertThat(data, Matchers.<Map<String, String>> hasItem(Matchers.hasKey("x")));

虽然这应该在没有Java 8中的显式类型参数的情况下工作。

答案 1 :(得分:0)

我认为他们更新了功能的签名。我发现我使用的是旧语法。

assertThat(singleParam)

assertThat(res.getStatus()).isEqualTo(200);

新的assertThat(actual, expected)

assertThat(res.getEntity(), is("Testing"));