While the top voted answer is correct, maybe I can add little more icing to the pie. So, in my case, I also wanted to verify upon clicking the link the correct intent is being sent out and I recently found out there is a very handy sub-library in espresso for this exact scenario:
androidTestImplementation 'com.android.support.test.espresso:espresso-intents:3.0.2'
In @After
method of test call Intents.init()
And in @Before
method of test call Intents.release()
And in @Test
method, do something like this -
@Test
fun testClickingUrlInTextView() {
// preparing
val link = "www.stackoverflow.com"
val expectingIntent = Matchers.allOf(IntentMatchers.hasAction(Intent.ACTION_VIEW), IntentMatchers.hasData(link));
// mocking intent to prevent actual navigation during test
Intents.intending(expectingIntent).respondWith(new ActivityResult(0, null));
// performing action
onView(Matchers.allOf(withId(R.id.textview), withText(link)))
.perform(openLinkWithText(link));
// asserting our expected intent was recorded
Intents.intended(expectingIntent);
}
So by structuring the test in the above manner, not only was I able to assert the navigating intent but also I was able to make the test less flaky in terms of it being able to run on any device regardless whether that device has the apps installed to handle that link. (Unless you want it to open in a specific app, which btw you can do as well by using the above espresso sub-lib.)