11

Here is the stub of the code.

Click data item on ListView . Works as designed and opens Chrome Custom Tab :

onData(anything()).inAdapterView(withId(R.id.listView))
                                       .atPosition(0).perform(click());

Pause(5000);
Espresso.pressBack();

Cannot seem to evaluate anything in the tab or even hit device back button. Getting this error

Error : android.support.test.espresso.NoActivityResumedException: No 
activities  in stage RESUMED.

Did you forget to launch the activity. (test.getActivity() or similar)?

reutsey
  • 1,743
  • 1
  • 17
  • 36
Sam Callejo
  • 121
  • 1
  • 3

3 Answers3

3

You can use UIAutomator (https://developer.android.com/training/testing/ui-automator.html). You can actually use both Espresso and UIAutomator at the same time. See the accepted answer on the following post for more information: How to access elements on external website using Espresso

reutsey
  • 1,743
  • 1
  • 17
  • 36
2

You can prevent opening Custom Tabs and then just assert whether the intent you are launching is correct:

fun stubWebView(uri: String) {
    Intents.intending(allOf(IntentMatchers.hasAction(Intent.ACTION_VIEW), IntentMatchers.hasData(uri)))
        .respondWith(Instrumentation.ActivityResult(Activity.RESULT_OK, null))
}

fun isNavigatedToWebView(uri: String) {
    Intents.intended(allOf(IntentMatchers.hasAction(Intent.ACTION_VIEW), IntentMatchers.hasData(uri)))
}

This way you can avoid Espresso.pressBack() in your test.

Note that since these are using Espresso Intents, you need to either use IntentsTestRule or wrap these with Intents.init and release like this

fun intents(func: () -> Unit) {
    Intents.init()

    try {
        func()
    } finally {
        Intents.release()
    }
}

intents {
    stubWebView(uri = "https://www.example.com")
    doSomethingSuchAsClickingAButton()
    isNavigatedToWebView(uri = "https://www.example.com")
}
Mustafa Berkay Mutlu
  • 1,929
  • 1
  • 25
  • 37
  • If you want you can also remove the `IntentMatchers.hasData(uri)` from the `stubWebView()` function and prevent opening *any* WebView (regardless of the URI). – Mustafa Berkay Mutlu May 12 '22 at 08:47
0

A suggestion for improved readability following Mustafa answer:

intents{
    Intents.intended(
        CoreMatchers.allOf(
            IntentMatchers.hasAction(Intent.ACTION_VIEW),
            IntentMatchers.hasPackage("com.android.chrome")
        )

    )
}
Gabriel Ferreira
  • 435
  • 6
  • 10