首页 > 解决方案 > 如何测试网页是否通过意图成功打开(Robolectric)

问题描述

我编写了以下代码,通过单击按钮在手机浏览器上打开一个 url

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

我正在尝试编写一个 Robolectric 测试,该测试仅在所需网页打开时才能通过,但我不确定如何执行此操作。这可能吗?

标签: androidrobolectric

解决方案


我正在尝试编写一个 Robolectric 测试,只有在所需的网页打开时才会通过

这是不可能的,但是(这实际上是您应该测试的)您可以检查是否 使用匹配的某些条件startActivity 调用了您。ContextIntent

假设您已将代码设计为可测试的,那么您应该有一个方法(或类),该方法(或类)采用 aContext和 an Urior String。我们将假设以下内容:

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

然后我们可以编写以下测试(注意:此示例使用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
      }
    )
  }

推荐阅读