Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use activityScenarioRule<Activity>?

I'm following the dev guide here:

https://developer.android.com/guide/components/activities/testing

and have a test class like:

@RunWith(AndroidJUnit4::class)
class MyTestSuite {
   @get:Rule var activityScenarioRule = activityScenarioRule<MyActivity>()

   @Test fun testEvent() {
    val scenario = activityScenarioRule.scenario
   }
}

the method activityScenarioRule<T>() is not defined. What dependency do I need? Also, what is the best way to determine which dependencies to add when reading these docs?

like image 225
Stephen__T Avatar asked Feb 26 '19 04:02

Stephen__T


People also ask

How do you get activity from Activityscenariorule?

You can access the ActivityScenario instance via getScenario() . You may finish your activity manually in your test, it will not cause any problems and this rule does nothing after the test in such cases. This rule is an upgraded version of the now deprecated ActivityTestRule .

How do you write unit testing activities?

To test an activity, you use the ActivityTestRule class provided by the Android Testing Support Library. This rule provides functional testing of a single activity. The activity under test will be launched before each test annotated with @Test and before any method annotated with @Before.

What is an activity scenario?

ActivityScenario provides APIs to start and drive an Activity's lifecycle state for testing. It works with arbitrary activities and works consistently across different versions of the Android framework. The ActivityScenario API uses Lifecycle.


2 Answers

The activityScenarioRule<T>() method is part of the androidx.test.ext:junit-ktx:1.1.0 dependency.

Usually, this would be listed under the List of AndroidX Test dependencies, but it appears it isn't up to date with the junit-ktx or core-ktx modules as of yet, despite it being explicitly mentioned as part of the Version 1.1.0-beta01 release notes

like image 159
ianhanniballake Avatar answered Oct 05 '22 16:10

ianhanniballake


If you are not using the ktx dependency, e.g. androidx.test.ext:junit:1.1.2 you can do it like this:

@get:Rule
var activityScenarioRule = ActivityScenarioRule(MyActivity::class.java)
like image 32
Jorge Guillermo Negrete Avatar answered Oct 05 '22 15:10

Jorge Guillermo Negrete