与 hamcrest 中的 contains 相反

opposite of contains in hamcrest

包含的反义词是什么?

    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_

JavaDoc 中,我可以看出一种笨拙的方法。可能有更好的方法!这测试列表是否不包含 a,不包含 b,以及 ...

List<Matcher> individual_matchers = new ArrayList<Matcher>();
for( String s : shouldNotBeInList ) {
    individual_matchers.add(Matchers.not(Matchers.contains(s)); // might need to use Matchers.contains({s}) - not sure
}
Matcher none_we_do_not_want = Matchers.allOf(individual_matchers);
Assert.assertThat(list, none_we_do_not_want);

(尚未测试,可能有问题:/希望对您有所帮助)

作为一种解决方法,可以使用以下方法:

list - shouldNotBeInList 应该等于列表本身(需要转换为集合)

    Set<String> strings = new HashSet<>(list);
    strings.removeAll(shouldNotBeInList);

    Set<String> asSet = new HashSet<>(list);
    Assert.assertTrue(strings.equals(asSet));

但我希望应该有更好的方法。

试试这个方法:

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

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

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

执行这个测试会给你:

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

我遇到了同样的问题。我的解决方案只是这场比赛的反逻辑。

下面是代码片段:

this.mockMvc.perform(get("/posts?page=0&size=1")
                .with(httpBasic(magelan.getUserName(), magelan.getPassword()))
                .accept(MediaType.parseMediaType("text/html;charset=UTF-8")))
                .andExpect(status().isOk())
                .andExpect(content().contentType("text/html;charset=UTF-8"))
                .andExpect(content().string(allOf(
                        containsString("First post")
                )))
                .andExpect(content().string(allOf(
                        not(containsString("Second post"))
                )));