-
Notifications
You must be signed in to change notification settings - Fork 53
Writing an Activity Test
Activity
testing on JUnit 5 is built on top of the Android ActivityScenario
API. This guide is a great introduction to how that particular API can be used to drive an instrumentation test.
The android-test-core
library provided by this repository gives developers an entry point to the ActivityScenario
through an Extension Point. Its usage is analogous to how the old ActivityScenarioRule
works in a JUnit 4 context.
Here is a minimal example:
class MyActivityTest {
@JvmField
@RegisterExtension
val scenarioExtension = ActivityScenarioExtension.launch<MyActivity>()
@Test
fun myTest() {
val scenario = scenarioExtension.scenario
// Do something with the scenario here...
}
}
Instead of being annotated with JUnit 4's @Rule
, the extension is annotated with @RegisterExtension
. For tests written in Kotlin, the @JvmField
is also required, so that the runtime can process the extension properly.
When you use the ActivityScenarioExtension
, you can also take advantage of JUnit 5's "parameter resolution" feature. A scenario can be passed to a test method directly as a parameter, saving you one line of code inside each test:
class MyActivityTest {
@JvmField
@RegisterExtension
val scenarioExtension = ActivityScenarioExtension.launch<MyActivity>()
@Test
fun myTest(scenario: ActivityScenario<MyActivity>) {
// Do something with the scenario here...
}
}
Note the method parameter of the myTest()
method.
For more information on ActivityScenario
, please refer to the official documentation on the topic.