在hamcrest中包含对面

时间:2016-10-12 14:38:00

标签: java 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_

5 个答案:

答案 0 :(得分:10)

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

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

执行此测试将为您提供:

  

预期:每个项目都不是{&#34; a&#34;,&#34; e&#34;,&#34; f&#34;,&#34; d&#34;}
  但是:一个项目是&#34; a&#34;

答案 1 :(得分:1)

试试这个方法:

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

答案 2 :(得分:0)

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

(尚未测试,可能是越野车:/希望它有帮助)

答案 3 :(得分:0)

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

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

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

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

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

答案 4 :(得分:0)

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

您可以看到以下代码片段:

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