Search code examples
javaunit-testingtestinghamcrest

why does my hamcrest "contains" not work as expected?


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?


Solution

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