Last active
April 3, 2017 17:02
-
-
Save passsy/ddb3b5611fd1b9457a444db8305d1736 to your computer and use it in GitHub Desktop.
How to test a parcelable in androidTest
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ParcelableTest extends AndroidTestCase { | |
/** | |
* Parcels the given Parcelable, unparcels it and returns the unparceled value | |
* | |
* @param value the Parcelable to operate on | |
*/ | |
public static Parcelable parcelAndUnparcel(Parcelable value) { | |
Parcel parcel = Parcel.obtain(); | |
value.writeToParcel(parcel, 0); | |
parcel.setDataPosition(0); | |
try { | |
Field creatorField = value.getClass().getField("CREATOR"); | |
Parcelable.Creator creator = (Parcelable.Creator) creatorField.get(value); | |
return (Parcelable) creator.createFromParcel(parcel); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
return null; | |
} finally { | |
parcel.recycle(); | |
} | |
} | |
public void testParceling() { | |
final MyParcel p = new MyParcel(); | |
assertEquals(p, parcelAndUnparcel(p)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment