パーセル ヘルパー クラスを使用して、オブジェクトをパーセルとの間で変換しています。
この要点を参照してください: https://gist.github.com/scallacs/f749a7385bcf75829a98d7b651efd02e
使い方はとても簡単です:
Model model = new Model("HelloWorld");
// Create an object from the parcel model
Model createdFromParcel = ParcelTestHelper.createFromParcel(model, model.CREATOR);
// Do your assertions...
assertEquals(model.value, createdFromParcel.value);
実装:
import android.os.Parcel;
import android.os.Parcelable;
public class ParcelTestHelper {
public static String DEFAULT_CREATOR_FIELD = "CREATOR";
public static <T extends Parcelable> T createFromParcel(T input, Parcelable.Creator<T> creator) {
Parcel parcel = toParcel(input);
return fromParcel(parcel, creator);
}
public static <T extends Parcelable> T createFromParcel(T input) throws NoSuchFieldException, IllegalAccessException {
return createFromParcel(input, getCreator(input));
}
public static <T extends Parcelable> Parcel toParcel(T input) {
Parcel parcel = Parcel.obtain();
input.writeToParcel(parcel, input.describeContents());
parcel.setDataPosition(0);
return parcel;
}
public static <T> Parcelable.Creator<T> getCreator(T input) throws NoSuchFieldException, IllegalAccessException {
return getCreator(input, DEFAULT_CREATOR_FIELD);
}
public static <T> Parcelable.Creator<T> getCreator(T input, String field) throws NoSuchFieldException, IllegalAccessException {
Object creator = input.getClass().getField(field).get(input);
if (!(creator instanceof Parcelable.Creator)) {
throw new InternalError("Should have field " + field + " instance of Parcelable.Creator");
}
return (Parcelable.Creator<T>) creator;
}
public static <T extends Parcelable> T fromParcel(Parcel parcel, Parcelable.Creator<T> creator) {
return creator.createFromParcel(parcel);
}
}