opposite of contains in hamcrest

pihentagy picture pihentagy · Oct 12, 2016 · Viewed 10.6k times · Source

What is the opposite of contains?

    List<String> list = Arrays.asList("b", "a", "c");
    // should fail, because "d" is not in the list

    expectedInList = new String[]{"a","b", "c", "d"};
    Assert.assertThat(list, Matchers.contains(expectedInList));


    // should fail, because a IS in the list
    shouldNotBeInList = Arrays.asList("a","e", "f", "d");
    Assert.assertThat(list, _does_not_contains_any_of_(shouldNotBeInList)));

what should be _does_not_contains_any_of_?

Answer

eee picture eee · Oct 12, 2016

You can combine three built-in matchers in the following way:

import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.not;

@Test
public void hamcrestTest() throws Exception {
    List<String> list = Arrays.asList("b", "a", "c");
    List<String> shouldNotBeInList = Arrays.asList("a", "e", "f", "d");
    Assert.assertThat(list, everyItem(not(isIn(shouldNotBeInList))));
}

Executing this test will give you:

Expected: every item is not one of {"a", "e", "f", "d"}
but: an item was "a"