With Espresso-Intents, how do intended and intending differ, and how do you test a sign-in screen that picks a phone number from the contacts app?
answer
- verify versus stub
- Mockito for intents
- record from init, release after
- the destination never opens
- exactly one match by default
basics
~20 sintended(matcher) verifies, like Mockito's verify, that the app sent exactly one matching activity intent; intending(matcher).respondWith(result) stubs it, so the external activity never opens and the app receives a canned ActivityResult. IntentsRule initialises and releases the recording around each test.
solid answer
~40 sEspresso-Intents (`espresso-intents`) records the intents your app uses to start activities, from `Intents.init()` until `Intents.release()`; `IntentsRule`, added in Espresso 3.5.0, calls both around each test. `intended(matcher)` is verification: it asserts that exactly one recorded intent matches, in any order, and `intended(matcher, times(n))` changes the count. `intending(matcher).respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, data))` is stubbing: a matching intent does not launch its destination, and the app gets the canned result. For the contact picker, stub `hasAction(Intent.ACTION_PICK)` with a result carrying the number, click the button with Espresso, check the phone field, and optionally `intended(...)` the pick. Without a stub, the real contacts app opens and the test leaves your process. Many suites add `intending(not(isInternal()))` with a neutral result so no external activity ever starts.
code
kotlin · 21 lines@RunWith(AndroidJUnit4::class)
class PhoneSignInTest {
@get:Rule(order = 0)
val intentsRule = IntentsRule()
@get:Rule(order = 1)
val activityRule = ActivityScenarioRule(PhoneSignInActivity::class.java)
@Test
fun pickedContactFillsPhoneField() {
val data = Intent().putExtra("phone", "+351 912 345 678")
intending(hasAction(Intent.ACTION_PICK))
.respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, data))
onView(withId(R.id.pick_contact)).perform(click())
intended(hasAction(Intent.ACTION_PICK))
onView(withId(R.id.phone)).check(matches(withText("+351 912 345 678")))
}
}go deeper
Recall the pairing: intended verifies an intent was sent, intending stubs the response so the other app never opens, and the intents rule wraps each test.
Explain init and release, the times(1) default of intended, how respondWith delivers an ActivityResult, and which IntentMatchers fit an action, a package or extras.
Build hermetic tests: stub external intents with isInternal, order the intents rule before the activity rule, cover cancelled results, and use assertNoUnverifiedIntents where every outgoing intent matters.
Be explicit about what stubbing proves: your side of a contract with another app. Decide where a separate check of the real handoff is still worth its cost.
## What Espresso-Intents is for Many screens hand work to another app: open a web page, dial a number, pick a contact, take a photo. An instrumented test cannot drive another app's UI reliably, and it should not depend on which contacts app the emulator has. **Espresso-Intents** is the Espresso extension that lets a test **validate** and **stub** the intents the app sends to start activities, so the test can focus on the app's own logic. Android's documentation describes it as Mockito for Android intents, and the two calls map onto Mockito's `verify` and `when`. It lives in the `androidx.test.espresso:espresso-intents` artifact. ## Turning recording on and off Recording starts at `Intents.init()` and is cleared by `Intents.release()`, which must run after each test. Calling `intended` or `intending` before `init()` fails with "Intents not initialized. Did you forget to call init()?". Two ways to manage this: - **`IntentsRule`**, added in Espresso 3.5.0, a JUnit rule that calls `init()` before each test and `release()` after it. Combine it with `ActivityScenarioRule` or `ActivityScenario` to launch the screen. If the screen sends an intent while it starts, make the intents rule run first, for example with `@get:Rule(order = 0)`. - **`IntentsTestRule`**, the older rule. It extends `ActivityTestRule` and is deprecated in favour of `IntentsRule` together with `ActivityScenario` or `ActivityScenarioRule`. ## intended: verification `intended(matcher)` asserts that the matcher matches **one and only one** recorded intent, the equivalent of Mockito's `verify(mock, times(1))`. Verification does not care about the order in which intents were sent, and it only sees intents recorded since `init()`. - A screen that sends the same intent twice fails a plain `intended(...)`; write `intended(matcher, times(2))`. - `assertNoUnverifiedIntents()` fails if any recorded intent was never verified, which keeps a test honest about everything the screen sends. - `intended` does **not** stop the destination from opening. If nothing stubs the intent, the real activity starts. ## intending: stubbing `intending(matcher).respondWith(result)` tells Espresso-Intents what to do when a matching intent is sent: the destination activity is **not** launched, and the result you supply is delivered to the app as if the other activity had finished with it. This is what makes a contact-picker test hermetic: the test never sees the contacts UI, and it decides exactly what comes back. The returned result matters for an activity the app started for a result; for any other matching intent the stub simply keeps the destination from opening. A stub typically looks like this: 1. Build the data: `val data = Intent().putExtra("phone", "+351 912 345 678")`. 2. Wrap it: `Instrumentation.ActivityResult(Activity.RESULT_OK, data)`. 3. Register it before the click: `intending(hasAction(Intent.ACTION_PICK)).respondWith(result)`. 4. Drive the UI with Espresso and check what the screen shows. Test the unhappy path too: a stub with `Activity.RESULT_CANCELED` and no data checks that the screen keeps the field empty and shows no error. ## Matching intents `IntentMatchers` provides the Hamcrest matchers both calls take: | Matcher | Matches on | |---|---| | `hasAction(...)` | the intent's action, such as `Intent.ACTION_PICK` or `Intent.ACTION_VIEW` | | `hasData(...)` | the data URI | | `hasComponent(...)` | an explicit target class | | `toPackage(...)` | the package the intent resolves to | | `hasExtra(...)` / `hasExtraWithKey(...)` | extras | | `isInternal()` | intents whose package is the app under test's own package | `isInternal()` enables a common safety net: in `@Before`, stub `intending(not(isInternal()))` with `Instrumentation.ActivityResult(Activity.RESULT_OK, null)` so no external activity can open during the test, then add specific stubs where a test needs real data. A stub registered later takes precedence for the intents it matches. ## Limits worth knowing - It records intents that **start activities**; broadcasts and service starts are outside it. - `intended` reads what has already been recorded, so it belongs after the action that sends the intent; called before it, it fails because nothing matches yet. - Rule order matters only for intents sent while the screen launches; intents sent after a click are recorded either way once recording has started. - It replaces the other app, so it proves your side of the contract only: that the intent is right and that your screen handles the result. Whether the contacts app really returns that shape is a separate question. - The real contacts picker returns a content URI that the app then queries; a test that returns an extra, as in Android's own example, is testing a simplified contract.
- Why does intended(hasAction(Intent.ACTION_VIEW)) fail when the screen opened the same link twice?`intended(matcher)` means `times(1)`: exactly one recorded intent must match. Two matching intents fail it just as zero would. If sending it twice is correct, write `intended(hasAction(Intent.ACTION_VIEW), times(2))`; if it is not, the failure has found a double-tap bug.
- How do you make sure no test in a class ever leaves the app for another app?In `@Before`, after `IntentsRule` has initialised recording, stub every intent outside your own package: `intending(not(isInternal())).respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, null))`. `isInternal()` matches intents for the app under test's package, so internal navigation still works while external activities are replaced. Individual tests add more specific stubs when they need real result data.
- Can Espresso-Intents verify a broadcast the screen sends?No. It records intents that start activities, from `Intents.init()` on. A broadcast or a service start is outside it, so verify those another way, for example through a fake injected where the app sends them.
- intending() verifies that the app sent a matching intent
- intended() also stubs the response so the other app never opens
- intended(matcher) passes as long as the intent was sent at least once
- IntentsTestRule is the current rule for new Espresso-Intents tests
- Espresso-Intents records broadcasts sent with sendBroadcast too
Assumes Espresso 3.7.0; IntentsRule was added in Espresso 3.5.0 and IntentsTestRule is deprecated in its favour.