Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 231
Ubaier Bhat Avatar asked Aug 13 '15 12:08

Ubaier Bhat


1 Answers

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
like image 74
vaughandroid Avatar answered Oct 12 '22 14:10

vaughandroid