使用Espresso进行测试

时间:2017-04-07 16:04:05

标签: android testing android-espresso

如何使用espresso为以下代码编写测试用例。我有以下代码,点击图标时执行。   我知道我可以使用预期(toPackage)来检查意图的启动(....如果通过startActivityForResult启动,可能会嘲笑意图的结果,但是如何处理这种情况。

try {
 intent = new Intent(Intent.ACTION_DIAL);
 intent.setData(Uri.parse("tel:" +"xxxxxx"); // 12 digit mobile no
    if (intent.resolveActivity(context.getPackageManager()) != null) {
                        startActivity(intent)
      }
    }
catch (Exception e) {
    Toast.makeText(getActivity(), "No phone number available", Toast.LENGTH_SHORT).show();
                }

1 个答案:

答案 0 :(得分:2)

答案是在测试代码后使用“预期”方法来验证活动结果是否符合您的要求。看起来像这样:

@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)));
}

但是,作为全自动测试的一部分,您还需要将对活动的响应存根,以便它可以在不需要实际阻止用户输入的情况下运行。您需要在运行测试之前设置意图存根:

@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的范围。由于我目前与帮助处理这类案件的供应商合作,我对名称和工具的名称犹豫不决,但很多人确实需要编写模拟真实端到端体验的测试。

迈克·埃文斯(Mike Evans)有一篇关于测试意图here的精彩文章,并且总是有文档here