Skip to content

Instantly share code, notes, and snippets.

@PaulWoitaschek
Created September 25, 2017 16:15
Show Gist options
  • Save PaulWoitaschek/41fb21b8bae1e731900867397813ace5 to your computer and use it in GitHub Desktop.
Save PaulWoitaschek/41fb21b8bae1e731900867397813ace5 to your computer and use it in GitHub Desktop.
import android.os.Parcel
import android.os.Parcelable
import org.assertj.core.api.Assertions.assertThat
/**
* A test for parcelable implementations
*/
class ParcelTester<T : Parcelable>(klazz: Class<T>) {
// access the creator through reflection like android does
@Suppress("UNCHECKED_CAST")
val creator = klazz.getField("CREATOR").get(null) as Parcelable.Creator<T>
// wraps a type to a parcel
fun wrap(value: T): Parcel {
val parcel = Parcel.obtain()
value.writeToParcel(parcel, 0)
parcel.setDataPosition(0)
return parcel
}
// unwraps a parcel
fun unwrap(parcel: Parcel): T = creator.createFromParcel(parcel)
fun repackageAndVerifyDataPosition(value: T): T {
val wrapped = wrap(value)
val unwrapped = unwrap(wrapped)
// check that the whole parcel was consumed
assertThat(wrapped.dataPosition()).isEqualTo(wrapped.dataSize())
return unwrapped
}
// test that the value is equal to itself after wrapping and unwrapping
fun test(value: T) {
val unwrapped = repackageAndVerifyDataPosition(value)
assertThat(value).isEqualTo(unwrapped)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment