繁体   English   中英

如何为 Android 中的深层链接编写测试?

[英]How to write tests for deep links in Android?

我想使用 UI 测试框架(Espresso)为带有深层链接案例的 Android 应用程序编写测试 - 仅使用 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()));
    }

}

我想仅使用深层链接启动测试应用程序,而无需标准启动。 你知道怎么做吗?

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

@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;
    }
};
@Rule
public ActivityTestRule<AppLauncherActivity> activityRule = new ActivityTestRule<>(AppLauncherActivity.class, false, false);

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

接受的答案是有帮助的,但现在ActivityTestRule类已被弃用

我们可以改用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))
    }

}

我还发现了这篇博客文章,其中包含其他示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM