Ubaier Bhat
Ubaier Bhat

Reputation: 854

Stubbing/mocking intent in Android Espresso test

I want to test the following flow in my application:

  1. The user clicks on a scan button
  2. onClick a ZXing app is launched
  3. If a correct qr code is returned we proceed else user gets an option to enter the code manually

I want to test this flow using espresso. I think I have to use intended or intending 1 but I an not sure how to check if the intent was ZXing and how to come back to the application.

Upvotes: 6

Views: 3233

Answers (1)

vaughandroid
vaughandroid

Reputation: 4374

The general flow to using espresso-intents is this:

  1. Call intending(X).respondWith(Y) in order to set up the mock.
  2. Perform the action which should result in the intent being sent.
  3. Call intended(Z) to verify that the mock received the expected intent.

X and Z could be identical, but I tend to make X as generalised as possible (e.g. only match the component name), and make Z be more specific (check values of extras, etc.).

e.g. For ZXing I might do something like this (warning: I haven't tested this code!):

Intents.intending(hasAction("com.google.zxing.client.android.SCAN"); // Match any ZXing scan intent
onView(withId(R.id.qr_scan_button).perform(click()); // I expect this to launch the ZXing QR scanner
Intents.intended(Matchers.allOf(
        hasAction("com.google.zxing.client.android.SCAN"),
        hasExtra("SCAN_MODE", "QR_CODE_MODE"))); // Also matchs the specific extras I'm expecting

Upvotes: 3

Related Questions