In hamcrest, Matchers.hasItem and friends returns a Matcher<Iterable<? super T>>, but contains and friends returns a Matcher<Iterable<? extends T>>. Why the difference?

1

There are 1 best solutions below

0
Lesiak On

My (handwavy) understanding is that the root cause is Naming of method Matchers#contains is ambiguous #140

In code reviews here, people often misread this:

assertThat(collection, contains("x"));

As meaning this: "Assert that the collection contains 'x'".

But what it actually means is this: "Assert that the collection contains only 'x'".

This causes a lot of unnecessary questions to be raised on our code reviews where code was updated to use Hamcrest, just because it reads differently to what it's actually doing.

At the same time, people looking to write new code with Hamcrest are using autocompletion to find appropriate-looking methods, and will often try to use contains before discovering that they really wanted hasItem.

I would suggest containsOnly as a new name, but containsInAnyOrder sort of has the same issue and I am finding it hard to jam the additional word in there.

Thus given:

class BaseFoo {}
class Foo1 extends BaseFoo {}
class Foo2 extends BaseFoo {}

Foo1 foo1 = new Foo1();
Foo2 foo2 = new Foo2();

Matcher<Iterable<? extends BaseFoo>> containsMatcher = Matchers.contains(foo1, foo2);
Matcher<Iterable<? super Foo1>> hasItemsMatcher = Matchers.hasItem(foo1);
  • containsMatcher will never match on an Iterable containing superclasses of BaseFoo
  • hasItemsMatcher can possibly match on an Iterable containing superclasses of BaseFoo

Also note that Matcher interface does not use its generic argument in its member methods (particularly in matches which accepts Object) - generic argument only matters when combining the Matchers.