Skip to content Skip to sidebar Skip to footer

How To Use Activitytestrule When Launching Activity With Bundle?

I am using val activityRule = ActivityTestRule(SingleFragmentActivity::class.java, true, true) and SingleFragmentActivity is a test helper activity class I used from google Git

Solution 1:

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

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

Solution 2:

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

The second approach doesn't require overriding ActivityRule:

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 */
    }
)

Solution 3:

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

@get:Rulevar rule: ActivityTestRule<YourActivity> =
        object : ActivityTestRule<YourActivity>(YourActivity::class.java) {
            overridefungetActivityIntent(): 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:Ruleval rule = ActivityTestRule(YourActivity::class.java,
    true,
    false) // launch activity later -> if its true, the activity will start here@TestfuntestFunction(){
        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

Post a Comment for "How To Use Activitytestrule When Launching Activity With Bundle?"