How to use ActivityTestRule when launching activity with bundle?

半世苍凉 提交于 2020-04-18 07:01:07

问题


I am using

  val activityRule = ActivityTestRule(SingleFragmentActivity::class.java, true, true)

and SingleFragmentActivity is a test helper activity class I used from google GithubBrowseSample

how can I launch activity with bundle ?


回答1:


You can get activity from activityRule and you can set extra data for intent

activityRule.activity.intent.putExtra("key",value)



回答2:


There are 2 ways of achieve what you would like to. First one, unfortunately, require creating custom ActivityRule, which will override some method.

  • ActivityTestRule.html#getActivityIntent()

The second approach doesn't require overriding ActivityRule:

  • ActivityTestRule.html#launchActivity(android.content.Intent)

but it requires passing false as a third parameter of ActivityRule constructor (launchActivity = false). In your case:

val activityRule = ActivityTestRule(SingleFragmentActivity::class.java, true, false)

I'd suggest the using the second approach, as then intent can be easily passed to ActivityRule but requires to start activity manually at test startup:

activityRule.launchActivity(
    Intent(context, SingleFragmentActivity::class.java).apply {
        /*put arguments */
    }
)



回答3:


You have 2 option. First: if you want the same intent (e.g. with the same extras) in every test.

    @get:Rule
    var rule: ActivityTestRule<YourActivity> =
        object : ActivityTestRule<YourActivity>(YourActivity::class.java) {
            override fun getActivityIntent(): Intent {
                val targetContext = InstrumentationRegistry.getInstrumentation().targetContext
                return Intent(targetContext, YourActivity::class.java).apply {
                    putExtra("someString","string")
                    putExtra("someBoolean",true)
               }
            }
         }

Second: if you want different intent (e.g. with different extras) in every test:

    @get:Rule
    val rule = ActivityTestRule(YourActivity::class.java,
    true,
    false) // launch activity later -> if its true, the activity will start here

    @Test
    fun testFunction(){
        val intent = Intent()
        intent.putExtra("name",value)
        intent.putExtra("someBoolean",false)
        rule.launchActivity(intent)
    }

source: http://blog.sqisland.com/2015/04/espresso-21-activitytestrule.html



来源:https://stackoverflow.com/questions/57588441/how-to-use-activitytestrule-when-launching-activity-with-bundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!