Skip to content

Writing an Activity Test

Marcel Schnelle edited this page Apr 7, 2019 · 4 revisions

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 compiler can process the extension properly.

Scenario as Parameter

When you use the ActivityScenarioExtension, you can also take advantage of JUnit 5's "parameter resolving" feature. A scenario can be passed into a test method directly, 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.

Clone this wiki locally