Search code examples
javahamcrest

opposite of contains in hamcrest


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_?


Solution

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