Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opposite of contains in hamcrest

Tags:

java

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

like image 611
pihentagy Avatar asked Oct 12 '16 14:10

pihentagy


People also ask

Does not contain assertion?

The Not Contains assertion verifies that some specific value is missing from the message.

Why are there Hamcrest matchers?

Purpose of the Hamcrest matcher framework. Hamcrest is a widely used framework for unit testing in the Java world. Hamcrest target is to make your tests easier to write and read. For this, it provides additional matcher classes which can be used in test for example written with JUnit.

What is org Hamcrest matchers in?

Hamcrest is the well-known framework used for unit testing in the Java ecosystem. It's bundled in JUnit and simply put, it uses existing predicates – called matcher classes – for making assertions.

What is a Hamcrest matcher?

Hamcrest is a framework that assists writing software tests in the Java programming language. It supports creating customized assertion matchers ('Hamcrest' is an anagram of 'matchers'), allowing match rules to be defined declaratively. These matchers have uses in unit testing frameworks such as JUnit and jMock.


2 Answers

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"

like image 181
eee Avatar answered Sep 28 '22 10:09

eee


Try this method :

public <T> Matcher<Iterable<? super T>> doesNotContainAnyOf(T... elements)
{
    Matcher<Iterable<? super T>> matcher = null;
    for(T e : elements)
    {
        matcher = matcher == null ?
            Matchers.not(Matchers.hasItem(e)) :
            Matchers.allOf(matcher, Matchers.not(Matchers.hasItem(e)));
    }
    return matcher;
}

With this test case :

List<String> list = Arrays.asList("a", "b", "c");
// True
MatcherAssert.assertThat(list, doesNotContainAnyOf("z","e", "f", "d"));
// False
MatcherAssert.assertThat(list, doesNotContainAnyOf("a","e", "f", "d"));
like image 41
ToYonos Avatar answered Sep 28 '22 08:09

ToYonos