Comparar objetos sin toString() mediante assertEquals

1
private void assertFieldsWithReflection(final Object expected, final Object actual)
2
throws InvocationTargetException, IllegalAccessException {
3
assertEquals(expected.getClass(), actual.getClass());
4
5
final List<java.lang.reflect.Method> getterMethods = getGetterMethods(actual.getClass());
6
for (final java.lang.reflect.Method getter : getterMethods) {
7
if (getter.getReturnType().isAssignableFrom(List.class)) {
8
assertListWithReflection(getter, expected, actual);
9
return;
10
}
11
12
final Object expectedValue = getter.invoke(expected);
13
final Object actualValue = getter.invoke(actual);
14
15
if (ClassUtils.isPrimitiveOrWrapper(getter.getReturnType())
16
|| getter.getReturnType().isAssignableFrom(String.class)
17
|| getter.getReturnType().isAssignableFrom(Enum.class)) {
18
assertEquals(expectedValue, actualValue);
19
} else {
20
if(expectedValue == null && actualValue == null){
21
return;
22
}
23
24
assertFieldsWithReflection(expectedValue, actualValue);
25
}
26
}
27
}
28
29
private void assertListWithReflection(
30
final java.lang.reflect.Method getter, final Object expectedValue, final Object actualValue)
31
throws InvocationTargetException, IllegalAccessException {
32
List<Object> expectedCollection = (List<Object>) getter.invoke(expectedValue);
33
List<Object> actualCollection = (List<Object>) getter.invoke(actualValue);
34
35
assertEquals(expectedCollection.size(), actualCollection.size());
36
37
for (int i = 0; i < expectedCollection.size(); i++) {
38
assertFieldsWithReflection(expectedCollection.get(i), actualCollection.get(i));
39
}
40
}
41
42
private List<java.lang.reflect.Method> getGetterMethods(final Class<?> clazz) {
43
return Arrays.stream(clazz.getMethods())
44
.filter(method -> method.getName().startsWith("get"))
45
.filter(method -> !method.getName().equals("getClass"))
46
.filter(method -> !Modifier.isStatic(method.getModifiers()))
47
.filter(method -> !method.getDeclaringClass().getPackage().getName().startsWith("java.security"))
48
.collect(Collectors.toList());
49
}