Search code examples
javajunit4assertassertions

How to use assertNotEquals for 2 lists of different size


I'm trying to assert two List of Strings having different number of elements. I'm testing an application and my goal is to Fail a test case if the Actual list contains even one element that matches the Expected list.

I have tried below approaches but none of these suffice my requirement.

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

I want this comparision yo fail since there is 1 element in actual list which matches the expected one.

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

None of these work. Any help would be appreciated.


Solution

  • This is a one-liner.

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

    The disjoint method returns true if its two arguments have no elements in common.

    It helps to know the libraries that come with the JDK. See http://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#disjoint-java.util.Collection-java.util.Collection-