Last active
August 28, 2024 10:14
-
-
Save tomaszpolanski/92a2eada1e06e4a4c71abb298d397173 to your computer and use it in GitHub Desktop.
Parcelize testing
This file contains hidden or 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.annotation.SuppressLint | |
import android.os.Parcelable | |
import kotlinx.android.parcel.Parcelize | |
@SuppressLint("ParcelCreator") // IntelliJ Issue https://youtrack.jetbrains.com/issue/KT-19300 | |
@Parcelize | |
data class Movie(val title: String) : Parcelable |
This file contains hidden or 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.support.test.runner.AndroidJUnit4 | |
import org.assertj.core.api.Assertions.assertThat | |
import org.junit.Test | |
import org.junit.runner.RunWith | |
@RunWith(AndroidJUnit4::class) | |
class MovieTest { | |
@Test | |
fun verify_parceling() { | |
val movie = Movie("Infinity War") | |
movie.testParcel() | |
.apply { | |
assertThat(this).isEqualTo(movie) | |
assertThat(this).isNotSameAs(movie) | |
} | |
} | |
} |
This file contains hidden or 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.Bundle | |
import android.os.Parcel | |
import android.os.Parcelable | |
inline fun <reified R : Parcelable> R.testParcel(): R { | |
val bytes = marshallParcelable(this) | |
return unmarshallParcelable(bytes) | |
} | |
inline fun <reified R : Parcelable> marshallParcelable(parcelable: R): ByteArray { | |
val bundle = Bundle().apply { putParcelable(R::class.java.name, parcelable) } | |
return marshall(bundle) | |
} | |
fun marshall(bundle: Bundle): ByteArray = | |
Parcel.obtain().use { | |
it.writeBundle(bundle) | |
it.marshall() | |
} | |
inline fun <reified R : Parcelable> unmarshallParcelable(bytes: ByteArray): R = unmarshall(bytes) | |
.readBundle() | |
.run { | |
classLoader = R::class.java.classLoader | |
getParcelable(R::class.java.name) | |
} | |
fun unmarshall(bytes: ByteArray): Parcel = | |
Parcel.obtain().apply { | |
unmarshall(bytes, 0, bytes.size) | |
setDataPosition(0) | |
} | |
private fun <T> Parcel.use(block: (Parcel) -> T): T = | |
try { | |
block(this) | |
} finally { | |
this.recycle() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The issue comes from
getParcelable
now correctly being annotated with@Nullable
.You can update the
unmarshallParcelable
return type toR?
to fix this issue.