方式1 launchActivity
val intent = Intent(ApplicationProvider.getApplicationContext(), YourActivity::class.java)
intent.putExtra("EXTRA_KEY", "extra_value")
val scenario = launchActivity<YourActivity>(intent)
// 读取
val extraData = scenario.result.getStringExtra("EXTRA_KEY")
assertEquals("extra_value", extraData)
方式2 setIntent
val intent = Intent(ApplicationProvider.getApplicationContext(), MyActivity::class.java)
intent.putExtra("myKey", "myValue")
val scenario = ActivityScenario.launch(MyActivity::class.java)
scenario.onActivity { activity ->
activity.setIntent(intent)
}
// 读取
val myValue = intent.getStringExtra("myKey")
方式3 custom intent factory
class CustomIntentFactory : androidx.test.core.app.ActivityScenario.IntentFactory {
override fun createIntent(context: Context, clazz: Class<*>): Intent {
val intent = Intent(context, clazz)
intent.putExtra("key", "value") // add extra data
return intent
}
}
@get:Rule
val activityScenarioRule = activityScenarioRule<MainActivity>(
intentFactory = CustomIntentFactory()
)
网友评论