的答案是使用“预期”的方法测试代码后,验证活动的结果符合您的要求,看起来像这样:
@Test
public void typeNumber_ValidInput_InitiatesCall() {
// Types a phone number into the dialer edit text field and presses the call button.
onView(withId(R.id.edit_text_caller_number))
.perform(typeText(VALID_PHONE_NUMBER), closeSoftKeyboard());
onView(withId(R.id.button_call_number)).perform(click());
// Verify that an intent to the dialer was sent with the correct action, phone
// number and package. Think of Intents intended API as the equivalent to Mockito's verify.
intended(allOf(
hasAction(Intent.ACTION_CALL),
hasData(INTENT_DATA_PHONE_NUMBER),
toPackage(PACKAGE_ANDROID_DIALER)));
}
但是,作为一个完全自动化测试的一部分,你需要将活动的响应也删除,以便它可以在没有实际阻止用户输入的情况下运行。您需要设置inten运行测试上前t存根:
@Before
public void stubAllExternalIntents() {
// By default Espresso Intents does not stub any Intents. Stubbing needs to be setup before
// every test run. In this case all external Intents will be blocked.
intending(not(isInternal())).respondWith(new ActivityResult(Activity.RESULT_OK, null));
}
然后,你可以这样写测试的相应部分:
@Test
public void pickContactButton_click_SelectsPhoneNumber() {
// Stub all Intents to ContactsActivity to return VALID_PHONE_NUMBER. Note that the Activity
// is never launched and result is stubbed.
intending(hasComponent(hasShortClassName(".ContactsActivity")))
.respondWith(new ActivityResult(Activity.RESULT_OK,
ContactsActivity.createResultData(VALID_PHONE_NUMBER)));
// Click the pick contact button.
onView(withId(R.id.button_pick_contact)).perform(click());
// Check that the number is displayed in the UI.
onView(withId(R.id.edit_text_caller_number))
.check(matches(withText(VALID_PHONE_NUMBER)));
}
如果需要从其他应用程序(如电话拨号与实际用户输入验证),这超出了Espresso的范围。由于我目前与一家帮助处理这类案件的供应商合作,我不愿意提供名称和工具,但很多人确实需要编写模拟真实端到端体验的测试。
迈克埃文斯有一个很好的关于测试意图here的文章,并且总是有android文档here。
我真的很感激你的答案,但我正在寻找解决问题的方法,我们使用startActivity而不是startActivityForResult启动拨号器活动。我曾经使用过类似的策略来嘲笑Camera Intent – cammando