Why does this not compile, oh, what to do?
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.hasItems;
ArrayList<
hasItems checks that a collection contains some items, not that 2 collections are equal, just use the normal equality assertions for that. So either assertEquals(a, b) or using assertThat
import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;
ArrayList<Integer> actual = new ArrayList<Integer>();
ArrayList<Integer> expected = new ArrayList<Integer>();
actual.add(1);
expected.add(2);
assertThat(actual, is(expected));
Alternatively, use the contains Matcher, which checks that an Iterable contains items in a specific order
import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.contains;
ArrayList<Integer> actual = new ArrayList<Integer>();
actual.add(1);
actual.add(2);
assertThat(actual, contains(1, 2)); // passes
assertThat(actual, contains(3, 4)); // fails
If you don't care about the order use containsInAnyOrder
instead.
That error message looks like one produced by the javac compiler. I've found in the past that code written using hamcrest just won't compile under javac. The same code will compile fine under, say, the Eclipse compiler.
I think Hamcrest's generics are exercising corner cases in generics that javac can't deal with.
You can get this error if you try to replace jUnit's hamcrest with a newer version. For example, using junit-dep together with hamcrest 1.3 requires that use assertThat from hamcrest instead of jUnit.
So the solution is to use
import static org.hamcrest.MatcherAssert.assertThat;
instead of
import static org.junit.Assert.assertThat;