Skip to content

Instantly share code, notes, and snippets.

@brescia123
Last active June 15, 2020 21:59
Show Gist options
  • Save brescia123/e5a919682f1460498bd72b87127d07d8 to your computer and use it in GitHub Desktop.
Save brescia123/e5a919682f1460498bd72b87127d07d8 to your computer and use it in GitHub Desktop.
Two custom ArgumentMatcher used to match Lists that contain elements without equals(). They use Mockito's ReflectionEquals to check elements equality.
/**
* Custom matcher that checks if a list is equal to expected when elements don't have equals()
* using {@link ReflectionEquals}.
*/
public static ArgumentMatcher<List> equalsList(List expectedList) {
return new ArgumentMatcher<List>() {
@Override
public boolean matches(Object argument) {
List list = (List) argument;
boolean assertion;
// Check size
return list.size() == expectedList.size() &&
containsAll(expectedList).matches(list) &&
containsAll(list).matches(expectedList);
}
};
}
/**
* Custom matcher that checks if a list contains all the expected elements when they don't have
* equals() using {@link ReflectionEquals}.
*/
public static ArgumentMatcher<List> containsAll(List expected) {
return new ArgumentMatcher<List>() {
@Override
public boolean matches(Object argument) {
List list = (List) argument;
boolean assertion;
for (Object expectedObject : expected) {
ReflectionEquals reflectionEquals = new ReflectionEquals(expectedObject, null);
assertion = false;
for (Object object : list) {
if (reflectionEquals.matches(object)) {
assertion = true;
break;
}
}
if (!assertion) return false;
}
return true;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment