与汉克斯特中的包含相反

2022-09-02 03:37:01

包含的反义词是什么?

    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)));

应该是什么?_does_not_contains_any_of_


答案 1

您可以通过以下方式组合三个内置匹配器:

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))));
}

执行此测试将为您提供:

预期:每个项目都不是 {“a”、“e”、“f”、“d”}
之一,而是:一个项目是 “a”


答案 2

试试这个方法:

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;
}

有了这个测试用例:

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"));

推荐