2

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?

Community
  • 1
  • 1
Elad Benda2
  • 13,852
  • 29
  • 82
  • 157

2 Answers2

3

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).

Stanislav
  • 27,441
  • 9
  • 87
  • 82
  • thanks, then how can I check if at least one item satisfies 2 matchers for example? because contains is the only one to get few matchers – Elad Benda2 Jul 05 '16 at 16:09
1

With hasItem, the iterable needs to have at least one item which matches the parameter matcher. In addition, it can have more items (matching or not), in any order. (The matcher is tried on each element until one of them matches, the rest is ignored.)

With contains, the iterable needs to have exactly the item (or items) which are matched by the parameter (or parameters), in the same order, and no others. (I.e. the first item needs to match the first parameter matcher, the second item the second parameter matcher, ... and the last item the last parameter matcher. Each matcher is tried on just one element.) With just one parameter, this means the iterable needs to have exactly one element.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
  • thanks, then how can I check if at least one item satisfies 2 matchers for example? because contains is the only one to get few matchers – Elad Benda2 Jul 05 '16 at 16:09
  • @EladBenda2 if I understand right (you want to make sure that there is an item which is matched by both matchers), have a look at `Matchers.both(matcher1).and(matcher2)`. – Paŭlo Ebermann Jul 07 '16 at 17:29