Skip to content

Instantly share code, notes, and snippets.

@richardleggett
Last active December 30, 2015 03:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardleggett/7771688 to your computer and use it in GitHub Desktop.
Save richardleggett/7771688 to your computer and use it in GitHub Desktop.
Forgetting to balance the Parcelable read/write calls can lead to inconsistent state. Here's some helper code for testing objects that implement Parcelable...
public void testParcelableThing() throws Exception {
// sample usage
MyParcelableThing parcelable = getTheThing();
Parcel parcel = Parcel.obtain();
parcelable.writeToParcel(parcel, 0);
parcel.setDataPosition(0);
MyParcelableThing unparcelled = new MyParcelableThing(parcel);
parcel.recycle();
// here's the trick - assuming your Parcelable object has getters for its props
assertGettersEqual(parcelable, unparcelled);
}
// helper methods
public List<Method> getGetterMethodList(Object obj) {
List<Method> methods = Arrays.asList(obj.getClass().getDeclaredMethods());
List<Method> getters = new ArrayList<Method>();
for (Method m : methods) {
String name = m.getName();
if (name.startsWith("get") || name.startsWith("is")) {
getters.add(m);
}
}
return getters;
}
public boolean assertGettersEqual(Object obj1, Object obj2) {
Class<?> obj2Class = obj2.getClass();
List<Method> getters = getGetterMethodList(obj1);
for (Method method : getters) {
Method method2;
try {
method2 = obj2Class.getDeclaredMethod(method.getName());
Object result1 = method.invoke(obj1);
Object result2 = method2.invoke(obj2);
boolean isEqual = true;
if((result1==null&&result2!=null || result1!=null&&result2==null) && result1!=null&&result2!=null) {
isEqual = false;
} else if(result1!=result2 && !result1.equals(result2)){
isEqual = false;
}
if(!isEqual) {
fail("getters not equal for: " + method.getName() + " expected: " + result1 + "\n but got\n " + result2);
return false;
}
} catch (Exception e) {
fail("Problem with reflection (does getter exist?): " + method.getName() + " reason: " + e);
return false;
}
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment