Why doesn't this code attempting to use Hamcrest's hasItems compile?

ripper234 picture ripper234 · Jul 7, 2009 · Viewed 79.4k times · Source

Why does this not compile, oh, what to do?

import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.hasItems;

ArrayList<Integer> actual = new ArrayList<Integer>();
ArrayList<Integer> expected = new ArrayList<Integer>();
actual.add(1);
expected.add(2);
assertThat(actual, hasItems(expected));

error copied from comment:

cannot find symbol method assertThat(java.util.ArrayList<java.lang.Integer>, org.hamcreset.Matcher<java.lang.Iterable<java.util.ArrayList<java.lang.Integer>>>)

Answer

Clive Evans picture Clive Evans · Sep 7, 2011

Just ran into this post trying to fix it for myself. Gave me just enough information to work it out.

You can give the compiler just enough to persuade it to compile by casting the return value from hasItems to a (raw) Matcher, eg:

ArrayList<Integer> actual = new ArrayList<Integer>();
ArrayList<Integer> expected = new ArrayList<Integer>();
actual.add(1);
expected.add(2);
assertThat(actual, (Matcher) hasItems(expected));

Just in case anybody else is still suffering ...

Edit to add: In spite of the up votes, this answer is wrong, as Arend points out below. The correct answer is to turn the expected into an array of Integers, as hamcrest is expecting:

    ArrayList<Integer> actual = new ArrayList<Integer>();
    ArrayList<Integer> expected = new ArrayList<Integer>();
    actual.add(1);
    expected.add(2);
    assertThat(actual, hasItems(expected.toArray(new Integer[expected.size()])));