4

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?

User1
  • 39,458
  • 69
  • 187
  • 265
  • only 3 upvotes for a question, about tests, that _every_ Android programmer should ask? I am ashamed of this industry! Everyone teach more testing! – Phlip Aug 08 '22 at 02:14

2 Answers2

2

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
0

I think they updated the function's signature. I found that I was using an old syntax.

old assertThat(singleParam)

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

new assertThat(actual, expected)

assertThat(res.getEntity(), is("Testing"));
earlonrails
  • 4,966
  • 3
  • 32
  • 47