Reputation: 115
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.
Upvotes: 0
Views: 1940
Reputation: 79876
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-
Upvotes: 1
Reputation: 22442
You can do this by using assertFalse
if any of the elements of actual list matches with any element in expected list as below:
@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);
}
}
}
Upvotes: 0
Reputation: 609
I think you want something like this:
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
}
Upvotes: 0
Reputation: 1518
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 contains any element in expected list or vice-versa.
Upvotes: 0