[英]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.