Josh Montgomery
Josh Montgomery

Reputation: 21

How to test if a web page was successfully opened via intent (Robolectric)

I wrote the following bit of code to open a url on the phone's browser on a button click

val intent = Intent(Intent.ACTION_VIEW, Uri.parse(uriString))
startActivity(intent)

I am trying to write a Robolectric test which will pass only if the desired web page is open, but am not sure how to do this. Is this possible?

Upvotes: 1

Views: 1220

Answers (1)

Droidman
Droidman

Reputation: 11608

I am trying to write a Robolectric test which will pass only if the desired web page is open

This is not possible, however (and this is actually what you should be testing) you can check whether startActivity was called on your Context using an Intent matching certain criteria.

Provided that you have designed your code to be testable, you should have a method (or class) that takes a Context and an Uri or String. We will assume the following:

fun openLink(context: Context, link: Uri){
  val intent = Intent(Intent.ACTION_VIEW, link)
  context.startActivity(intent)
}

Then we could write the following test (note: this example uses mockito-kotlin):

@Test
fun `verify intent was broadcast`(){
  val context: Context = mock()
  val expectedLink = "https://google.com"
  val uri: Uri = mock()
  whenever(uri.toString()).thenReturn(expectedLink)
  tested.openLink(context, uri) // "tested" is the instance of your class under test
  verify(context).startActivity(
    argThat {
      this.action == Intent.ACTION_VIEW &&
          this.dataString!! == expectedLink
      }
    )
  }

Upvotes: 1

Related Questions