Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"no suitable method found" when using hasItem Hamcrest Matcher

Tags:

java

hamcrest

When I run the following jUnit test:

@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")));
}

I get this:

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)

It looks like something in the generics is breaking down. What is it?

like image 663
User1 Avatar asked Sep 01 '25 16:09

User1


1 Answers

javac doesn't know how to infer the generic type for some of those methods.

assertThat expects a value and a Matcher of that type. You'll have to be explicit

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

Though this should work without the explicit type argument in Java 8.

like image 189
Sotirios Delimanolis Avatar answered Sep 04 '25 05:09

Sotirios Delimanolis