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_
?
The Not Contains assertion verifies that some specific value is missing from the message.
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.
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.
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.
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"
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"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With