Question

I have a question

I want to test whether after button click the web browser is beign launched using espresso. And the question is: is it even possible to test such thing? If so any ideas how would I do that?

Was it helpful?

Solution 3

Actually no. Espresso will allow you to click in the button and once the browser is fired up, the test will end. The alternative you have is having your class that fires the browser Intent mocked, so that you can test the remaining flow (if any).

HAve a look in this answer: Controlling when an automation test ends - Espresso, where I describe how you could achieve that.

OTHER TIPS

Although it's an old question but just posting here to help anyone else. I had the same situation where i wanted to verify whether a particular url was launched in browser or not. I got real help from this link

I got it working using this chunk of code:

    Intents.init();
    Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(EXPECTED_URL));
    intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null));
    onView(withId(R.id.someid)).perform(click());
    intended(expectedIntent);
    Intents.release();

So, it tests when browser is opened with correct url and intending() does the magic here by enabling intent stubbing. Using this, we can intercept it so the intent is never sent to the system.

For convenience I suggest a full example:


Production code:

register_terms.text = Html.fromHtml(getString(R.string.register_terms,
        getString(R.string.privacy_policy_url),
        getString(R.string.register_terms_privacy_policy),
        getString(R.string.general_terms_and_conditions_url),
        getString(R.string.register_terms_general_terms_and_conditions)))

Strings XML:

<string name="register_terms">By registering you accept our &lt;a href=\"%1$s\">%2$s&lt;/a&gt; and the &lt;a href=\"%3$s\">%4$s&lt;/a&gt;.</string>
<string name="register_terms_privacy_policy">Privacy Policy</string>
<string name="register_terms_general_terms_and_conditions">General Terms and Conditions</string>

<string name="privacy_policy_url" translatable="false">https://www.privacypolicy.com</string>
<string name="general_terms_and_conditions_url" translatable="false">https://www.generraltermsandconditions.com</string>

Test code:

@Before
fun setUp() {
    Intents.init()
}

@After
fun tearDown() {
    Intents.release()
}

@Test
fun when_clickPrivacyLink_then_openPrivacyUrl() {
    val expected = allOf(IntentMatchers.hasAction(Intent.ACTION_VIEW), IntentMatchers.hasData(string(privacy_policy_url)))
    Intents.intending(expected).respondWith(Instrumentation.ActivityResult(0, null))

    onView(ViewMatchers.withId(R.id.register_terms))
            .perform(openLinkWithText(string(register_terms_privacy_policy)))

    Intents.intended(expected)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top