Skip to content

Instantly share code, notes, and snippets.

@mandybess
Created May 27, 2016 22:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mandybess/4da06755188b3a191de3c1403c8f1532 to your computer and use it in GitHub Desktop.
Save mandybess/4da06755188b3a191de3c1403c8f1532 to your computer and use it in GitHub Desktop.
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
public class TestHelper {
public static void assertReflectiveEquals(String message, Object expected, Object actual) {
String assertionMessage = "Classes are not equal";
if (message != null) {
assertionMessage = message + "; " + assertionMessage;
}
assertEquals(assertionMessage, expected.getClass(), actual.getClass());
List<String> notEqualFields = Lists.newArrayList();
for (Field field : expected.getClass().getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
try {
field.setAccessible(true);
Object expectedValue = field.get(expected);
Object actualValue = field.get(actual);
if (!Objects.equal(expectedValue, actualValue)) {
notEqualFields.add(
field.getName() + " is not equal (expected = " + field.get(expected) +
", actual = " + field.get(actual) + ")");
}
} catch (IllegalAccessException e) {
fail();
}
}
assertTrue(Joiner.on(", ").join(notEqualFields), notEqualFields.isEmpty());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment