Search code examples
javamatcherhamcrest

are `Matchers.hasItem` and `Matchers.contains` the same?


I saw this post

about the difference between:

Matchers.hasItem(..)

Assert.assertThat(items, Matchers.hasItem(Matchers.hasToString("c")));
which states

and

Matchers.contains

But I still don't get the difference. They both look for one predicate satisfaction. No?


Solution

  • They are almost the same, but Matchers.hasItem as said

    will stop as soon as a matching item is found

    Then Matchers.contains

    the examined iterable must only yield one item

    The difference is that first one checks whether there is at least one item (may be two or more), but the second one checks that there is exactly one item (only one, no more).