Created
September 25, 2017 16:15
-
-
Save PaulWoitaschek/41fb21b8bae1e731900867397813ace5 to your computer and use it in GitHub Desktop.
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
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