Using Espresso to Test Opening Links
Writing a regression test for clicking an autolink
Android Smartphone by freestocks.org is licensed under CC0
Imagine you have an app where a user can click on links to either open them in a browser, or make a phone call. We’ll even say this is an important functionality of your app. If this is the case, it would be smart to have a test for this to make sure it continues working and nothing breaks it in the future. Regression tests are good for this.
I ran across this exact situation when I wanted to write a regression test for clicking an autolink in a TextView to open it.
I already know how to use Espresso Intents to ensure an intent was fired without actually launching the Activity. In fact, I have a whole blog post about it.
Intents.init() val expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(correct_url)) intending(expectedIntent).respondWith(Instrumentation.ActivityResult(0, null)) // Click on link intended(expectedIntent) Intents.release()
Where I had to start looking was how to click on this link. Because the link was only a part of the full text view, I couldn’t use withText
or withId
with perform(click())
to click on this link. This would also be an issue if there were multiple links in the same text view.
I was able to find openLinkWithText
to work well for this situation. By using openLinkWithText, I could click on the link specifically, then test that the correct intent was fired with the correct information.
Intents.init() val expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(correct_url)) intending(expectedIntent).respondWith(Instrumentation.ActivityResult(0, null)) onView(withId(R.id.textView)) .perform(openLinkWithText("www.collectiveidea.com")) intended(expectedIntent) Intents.release()
Now we have our regression test to make sure the user will always be able to click a link or phone number to open it in this place within the app! We can be at peace that this functionality will not change in the future as long as we are running our tests.
Comments
Great, simple post that addresses my current testing concern. I’ll give it a try!