【问题标题】:How to write tests for deep links in Android?如何为 Android 中的深层链接编写测试?
【发布时间】:2017-03-22 12:08:00
【问题描述】:

我想使用 UI 测试框架 (Espresso) 为 Android app with deep link cases 编写测试 - 仅使用 ACTION_VIEW 意图启动应用程序并检查打开屏幕上的所有视图。

但是看起来 Espresso(甚至 espresso-intents)没有这个功能,需要定义 Activity 类。

我尝试过这种方式,但它不能正常工作,因为启动了两次应用 - 使用 AppLauncherActivity 标准启动(Espresso 需要)并通过深层链接启动。

@RunWith(AndroidJUnit4.class)
public class DeeplinkAppLauncherTest {

    @Rule
    public ActivityTestRule<AppLauncherActivity> activityRule = new ActivityTestRule<>(AppLauncherActivity.class);

    @Test
    public void testDeeplinkAfterScollDownAndBackUp() {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("myapp://search/777"));
        activityRule.launchActivity(intent);

        onView(withId(R.id.search_panel)).check(matches(isDisplayed()));
    }

}

我想仅使用深层链接而不使用标准启动来启动测试应用。 你知道怎么做吗?

【问题讨论】:

标签: android deep-linking android-testing android-espresso


【解决方案1】:

我找到了一个选项 - 只是为现有意图添加了深层链接打开参数并使用标准活动启动:

@Rule
public ActivityTestRule<AppLauncherActivity> activityRule = new ActivityTestRule<AppLauncherActivity>(AppLauncherActivity.class){
    @Override protected Intent getActivityIntent() {
        Intent intent = super.getActivityIntent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setData(Uri.parse("myapp://search/777"));
        return intent;
    }
};

【讨论】:

    【解决方案2】:
    @Rule
    public ActivityTestRule<AppLauncherActivity> activityRule = new ActivityTestRule<>(AppLauncherActivity.class, false, false);
    

    有多个构造函数用于创建 ActivityTestRule。第三个是launchActivity。如上所示将其设置为 false,因为您随后使用 activityRule.launchActivity(intent) 手动启动该活动。这应该可以防止它启动两次

    【讨论】:

      【解决方案3】:

      已接受的答案很有帮助,但如今 ActivityTestRule 类已成为 deprecated

      我们可以改用ActivityScenario

      这是一个 Kotlin 示例:

      class MyDeepLinkTest {
      
          private lateinit var scenario: ActivityScenario<LoadingActivity>
      
          @Before
          fun setUp() {
              Intents.init()
          }
      
          @After
          fun tearDown() {
              Intents.release()
              scenario.close()
          }
      
          @Test
          fun myTest() {
              val intent = Intent(ApplicationProvider.getApplicationContext(), LoadingActivity::class.java)
                  .putExtra("example_extra1", "Value 1")
                  .putExtra("example_extra2", 777)
      
              scenario = ActivityScenario.launch(intent)
      
              // Test code goes here (e.g. intent causes to start MainActivity)
              intended(hasComponent(MainActivity::class.java.name))
          }
      
      }
      

      我还发现了这个blog post 以及其他示例。

      【讨论】:

        猜你喜欢
        • 2022-01-19
        • 2019-07-01
        • 1970-01-01
        • 2022-11-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-24
        相关资源
        最近更新 更多