5

I run this line:

List<String> ids = new List<String>()
ids.add("id1");
ids.add("id2");
assertThat(ids, contains("id1"));

but strangely it returns "fail".

how can I fix this?

watery
  • 5,026
  • 9
  • 52
  • 92
Elad Benda2
  • 13,852
  • 29
  • 82
  • 157

1 Answers1

6

You need to use

assertThat(ids, hasItem(equalTo("id1"));

This is because contains will expect you to have a matcher that matches every item in the iterable.

If you look at the api docs here You can see the difference between contains and hasItem. If your list was as following:

List<String> ids = new List<String>()
ids.add("id1");

Your assertion would work as you would expect.

Paul Harris
  • 5,769
  • 1
  • 25
  • 41
  • You can drop the call to `equalTo`. All matchers that accept other matchers as parameters will wrap non-matchers with it. – David Harkness Aug 14 '14 at 02:49
  • Yeah you can drop it but it is more readable and more explicit about what you are testing which is why I added it in. – Paul Harris Aug 14 '14 at 05:18