如何将 assertNotEquals 用于 2 个不同大小的列表

How to use assertNotEquals for 2 lists of different size

我正在尝试断言两个具有不同元素数量的字符串列表。 我正在测试一个应用程序,我的目标是如果实际列表包含一个与预期列表匹配的元素,则测试用例失败。

我尝试了以下方法,但其中 none 可以满足我的要求。

List<String> expected = Arrays.asList("fee", "fi", "foe", "foo");
List<String> actual = Arrays.asList("feed", "fi"); 
assertThat(actual, not(equalTo(expected)));`

我希望这次比较失败,因为实际列表中有 1 个元素与预期的元素匹配。

Assert.assertNotEquals(actual,expected);
assertThat(actual, is(not(expected)));
Assert.assertNotEquals(actual, containsInAnyOrder(expected));

None 这些作品。任何帮助将不胜感激。

List<String> commonElement = findCommon(actual,expected);    
public List<String> findCommon(List<String> list1, List<String> list2) {
        List<String> list = new ArrayList<String>();

        for (String t : list1) {
            if(list2.contains(t)) {
                list.add(t);
            }
        }

        return list;
    }

Assert.assertTrue(commonElement.size() != 0); //This will fail when actual`

列表包含预期列表中的任何元素,反之亦然。

我想你想要这样的东西:

    List<String> expected = Arrays.asList("fee", "fi", "foe", "foo");
    List<String> actual = Arrays.asList("feed", "fi");

    assert(actual.size() != expected.size()); // Will fail if same number of elements
    for(String s : actual){
        assert(!expected.contains(s)); // Fails if element in actual is in expected
    }

如果实际列表中的任何元素与预期列表中的任何元素匹配,您可以使用 assertFalse 执行此操作,如下所示:

    @Test
    public void test() throws Exception{
        List<String> expected = Arrays.asList("fee", "fi", "foe", "foo");
        List<String> actual = Arrays.asList("feed", "fi1"); 
        for(String temp : expected) {
            if(!actual.stream().noneMatch((String s) -> s.equals(temp))) {
                Assert.assertFalse(true);
            }
        }
    }

这是单行本。

Assert.assertTrue(Collections.disjoint(list1, list2));

disjoint 方法 returns true 如果它的两个参数没有共同的元素。

了解 JDK 附带的库会有所帮助。参见 http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#disjoint-java.util.Collection-java.util.Collection-