Lists with RecyclerViewActions, and Espresso-Intents
On this page
The last chapter ended with two problems from the product list: "Product 42" could not be found because its row did not exist yet, and "Add" matched ten buttons at once. Both come from the same design: a RecyclerView only creates views for the rows on screen and recycles them as you scroll. Espresso solves it with list-aware actions. The second half of this chapter handles the other thing a screen often does that a test cannot follow: open another app.
Add espresso-contrib#
The list actions live in a separate artifact. Add it next to espresso-core in app/build.gradle.kts:
androidTestImplementation("androidx.test.espresso:espresso-contrib:3.7.0")
Keep every androidx.test.espresso artifact on the same version. Mixing, for example, espresso-core 3.7.0 with an older espresso-contrib, invites class conflicts that show up as odd NoSuchMethodErrors at run time.
RecyclerViewActions#
RecyclerViewActions are actions you perform() on the RecyclerView itself, not on a row. They work on the adapter's positions and data, so they can reach rows that have no view yet. The main ones:
| Action | What it does |
|---|---|
scrollTo<VH>(itemMatcher) |
Scrolls until a row matching the matcher is on screen |
scrollToPosition<VH>(42) |
Scrolls to a position |
actionOnItem<VH>(itemMatcher, action) |
Scrolls to the matching row, then performs the action on it |
actionOnItemAtPosition<VH>(41, action) |
Scrolls to a position, then performs the action |
The type parameter is the adapter's ViewHolder type; RecyclerView.ViewHolder works for any adapter. The item matcher is matched against the row's view, so hasDescendant(withText("Product 42")) means "the row that contains a view with the text Product 42".
Scrolling to the last product and checking it is visible:
@Test
fun lastProductIsReachable() {
onView(withId(R.id.products)).perform(
scrollTo<RecyclerView.ViewHolder>(hasDescendant(withText("Product 50")))
)
onView(withText("Product 50")).check(matches(isDisplayed()))
}
After the scroll, the row exists, so an ordinary onView can find it.
A chat screen shows messages in a RecyclerView. You need to check that the 200th message says "See you". What is the most direct approach?
Positions are zero-based, so the 200th message is position 199. The RecyclerView action scrolls by position without a view having to exist. scrollTo() on a row that has no view yet fails with NoMatchingViewException, and a fixed number of swipes breaks as soon as message heights change.
Tapping a button inside a row#
actionOnItem(itemMatcher, click()) taps the centre of the row. In Espresso Shop the centre of a row is the product name, not the Add button, so a plain click() would do nothing useful. Tests need to tap a specific child view of the row. Espresso has no built-in action for that, and this small custom ViewAction is the common way to write it:
fun clickChildViewWithId(id: Int): ViewAction = object : ViewAction {
override fun getConstraints(): Matcher<View> = isAssignableFrom(View::class.java)
override fun getDescription() = "click child view with id $id"
override fun perform(uiController: UiController, view: View) {
view.findViewById<View>(id).performClick()
}
}
perform() receives the row's view, finds the Add button inside it and clicks it. getDescription() is what Espresso prints in error messages, so make it say what the action does. Now the test that failed in the last chapter:
@Test
fun addsAnItemFarDownTheList() {
onView(withId(R.id.products)).perform(
actionOnItem<RecyclerView.ViewHolder>(
hasDescendant(withText("Product 42")),
clickChildViewWithId(R.id.add)
)
)
onView(withId(R.id.basket)).check(matches(withText("Basket: Product 42")))
}
And by position, chaining two actions on the list:
@Test
fun addsTwoItems() {
onView(withId(R.id.products))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(0, clickChildViewWithId(R.id.add)))
.perform(actionOnItemAtPosition<RecyclerView.ViewHolder>(1, clickChildViewWithId(R.id.add)))
onView(withId(R.id.basket)).check(matches(withText("Basket: Product 1, Product 2")))
}
Prefer matching rows by content (hasDescendant(withText(...))) over positions when the order can change, such as sorted or server-driven lists. Positions are fine for fixed data, like the first two rows of a static list.
These tests start ProductsActivity directly, without logging in, by giving ActivityScenarioRule an Intent with the extra the screen expects:
private val intent = Intent(
ApplicationProvider.getApplicationContext(),
ProductsActivity::class.java
).putExtra(ProductsActivity.EXTRA_USER, "alice")
@get:Rule
val activityRule = ActivityScenarioRule<ProductsActivity>(intent)
Starting each screen directly keeps tests short and independent: a list test should not fail because the login screen broke. One test of the full journey (chapter 2's login test) is enough.
The basket in Espresso Shop is saved in SharedPreferences, so it survives restarts. That turns out to matter: run these tests in one go and some of them fail, because the basket from one test is still there in the next. Chapter 5 is about exactly that.
Espresso-Intents: tests that do not leave the app#
The products screen has a Help button that opens the support page in a browser:
findViewById<Button>(R.id.help).setOnClickListener {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(HELP_URL)))
}
Tapping it in a test would open Chrome, which is outside the app. Espresso cannot see it, the test cannot get back reliably, and you do not want to test Chrome anyway. What you want to check is that the app asked for the right page. Espresso-Intents records every intent the app sends and lets you stub the answers. Add it:
androidTestImplementation("androidx.test.espresso:espresso-intents:3.7.0")
Then the test:
@RunWith(AndroidJUnit4::class)
class HelpLinkTest {
private val intent = Intent(
ApplicationProvider.getApplicationContext(),
ProductsActivity::class.java
)
@get:Rule
val rules: RuleChain = RuleChain
.outerRule(IntentsRule())
.around(ActivityScenarioRule<ProductsActivity>(intent))
@Test
fun helpOpensTheSupportPageInABrowser() {
val opensBrowser = allOf(
hasAction(Intent.ACTION_VIEW),
hasData(Uri.parse("https://testingbot.com/support"))
)
// Stub the browser so the test never leaves the app.
intending(opensBrowser).respondWith(ActivityResult(Activity.RESULT_OK, null))
onView(withId(R.id.help)).perform(click())
intended(opensBrowser)
}
}
The two halves:
-
intending(matcher).respondWith(result)is set up before the action. Any intent matching it is intercepted: the browser never starts, and the app receives the result you gave, as if the user had come back from it. This is also how you test screens that start the camera or a contact picker withActivityResultLauncher: return a fake photo or contact in theActivityResult. -
intended(matcher)comes after the action and verifies that the app sent a matching intent. It fails if none matched, and prints every intent that was recorded.
IntentsRule starts recording before each test and stops after it. It must wrap the activity rule, which is what RuleChain.outerRule(...).around(...) does. If recording starts after the activity has launched, intents sent during launch are missed.
A Share button sends an ACTION_SEND intent. The test calls intended(hasAction(Intent.ACTION_SEND)) after the click, but every run also opens the system share sheet on the device, and the next test starts behind it. What is missing?
intended only verifies; it does not stop the intent. Without an intending stub the intent goes through and the system UI opens. Stub it before the click and the sheet never appears.
You now have tests for every screen of Espresso Shop. Except the login tests, which still fail. Time to fix them.