簡體   English   中英

如何檢查發送的預期意圖而不是在Espresso中實際啟動活動?

[英]How to check expected intent sent without actually launching activity in Espresso?

我有一個UI測試點擊按鈕,然后在其onClickListener中啟動一個新的Activity。 該測試檢查是否發送了預期意圖。

我的問題是,我想測試是否在沒有實際啟動活動的情況下發送預期意圖。 因為我發現新活動初始化了它的狀態,並且后續測試變得不穩定。

我知道有兩種Espresso Intents api,它們都是intendedintending ,但都無法滿足我的需求。 intended api實際上啟動目標活動,並且intending api不啟動活動,但它調用onActivityResult回調,我也不想要。 因為我擔心onActivityResult中的代碼可能會導致另一個瑕疵。 同時intending言是否發送匹配意圖,它只是在找到匹配意圖時調用onActivityResult回調,這意味着我必須檢查onActivityResult是否被調用!

有沒有什么干凈的方法來實現我想要的?

如果要測試是否在未實際啟動活動的情況下發送預期意圖,可以通過使用activityResult捕獲意圖然后捕獲活動來執行此操作:

Intent intent = new Intent();
ActivityResult intentResult = new ActivityResult(Activity.RESULT_OK,intent);

intending(anyIntent()).respondWith(intentResult);

onView(withId(R.id.view_id_to_perform_clicking)).check(matches(isDisplayed())).perform(click());

intended(allOf(hasComponent(ActivityToBeOpened.class.getName())));

這將捕獲任何啟動ActivityToBeOpened的嘗試。 如果您想要更具體,您還可以使用Extras捕獲意圖:

intended(allOf(hasComponent(ActivityToBeOpened.class.getName()), hasExtra("paramName", "value")));

希望有所幫助。

Espresso的Intents課程簡潔而方便,但如果它不能滿足您的需求,還有另一種選擇。 如果使用AndroidJUnit4測試運行器,則可以使用InstrumentationRegistry.getInstrumentation()獲取Instrumentaion實例,然后可以添加Instrumentation.ActivityMonitor實例。

Instrumentation.ActivityMonitor am = new Instrumentation.ActivityMonitor("YOUR_ACTIVITY", null, true);
InstrumentationRegistry.getInstrumentation().addMonitor(am);
onView(withId(R.id.view_id_to_perform_clicking)).check(matches(isDisplayed())).perform(click());
assertTrue(InstrumentationRegistry.getInstrumentation().checkMonitorHit(am, 1));

ActivityMonitor構造函數的第三個參數告訴我們要阻止活動啟動。 請注意,這種方法有其局限性。 與Espresso Intents 豐富的Matcher支持相比 ,您無法為ActivityMonitor設置多個條件。

您可以在ApiDemos中找到幾個示例,尤其是在ContactsSelectInstrumentation類中。

實際上,您可以阻止任何啟動外部或您自己活動的意圖,但仍然使用豐富的Espresso Intents API:

    Instrumentation.ActivityMonitor soloMonitor = solo.getActivityMonitor();
    instrumentation.removeMonitor(soloMonitor);
    IntentFilter filter = null;
    // Block any intent
    Instrumentation.ActivityMonitor monitor = instrumentation.addMonitor(filter, null, true);
    instrumentation.addMonitor(soloMonitor);

    // User action that results in an external browser activity being launched.
    user.clickOnView(system.getView(R.id.callButton));
    instrumentation.waitForIdleSync();

    Intents.intended(Matchers.allOf(
            IntentMatchers.hasAction(Matchers.equalTo(Intent.ACTION_VIEW)),
            IntentMatchers.hasData(Matchers.equalTo(Uri.parse(url))),
            IntentMatchers.toPackage(chromePackage)));

    instrumentation.removeMonitor(monitor);

你能夠做到這一點,因為即使你阻止它們,Espresso Intents仍然會記錄每個Intent和IntentMonitor回調。 查看Espresso Intents的源代碼,了解他們如何做到這一點。

如果您使用Robotium Solo框架,則需要在自己的ActivityMonitor之前移動它。 否則只需跳過與此相關的行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM