在Android Kotlin测试中,可以使用以下方法为Intent的putExtra方法设置值:
val intent = Intent()
intent.putExtra("key", "value")
intent.putExtra("count", 10)
intent.putExtra("isSuccess", true)
data class User(val name: String, val age: Int) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString() ?: "",
parcel.readInt()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(name)
parcel.writeInt(age)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator {
override fun createFromParcel(parcel: Parcel): User {
return User(parcel)
}
override fun newArray(size: Int): Array {
return arrayOfNulls(size)
}
}
}
val user = User("John", 25)
intent.putExtra("user", user)
data class Product(val name: String, val price: Double) : Serializable
val product = Product("Phone", 500.0)
intent.putExtra("product", product)
注意:在测试中,可以使用Intent的getStringExtra、getIntExtra、getBooleanExtra等方法获取putExtra设置的值,并进行断言或验证。
val value = intent.getStringExtra("key")
assertEquals("value", value)
val count = intent.getIntExtra("count", 0)
assertEquals(10, count)
val isSuccess = intent.getBooleanExtra("isSuccess", false)
assertTrue(isSuccess)
val user = intent.getParcelableExtra("user")
assertEquals("John", user?.name)
assertEquals(25, user?.age)
val product = intent.getSerializableExtra("product") as? Product
assertEquals("Phone", product?.name)
assertEquals(500.0, product?.price)