使用 Espresso 进行测试

Testing using Espresso

如何使用 espresso 为以下代码编写测试用例。我有以下代码,单击图标时会执行这些代码。 我知道我可以使用 intended(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();
                }

一个答案是在你的测试代码之后使用'intended'方法来验证activity结果是否满足你的要求。看起来像这样:

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

但是,作为全自动测试的一部分,您还需要将对 activity 的响应存根,这样它就可以 运行 而无需实际阻止用户输入。您需要在 运行 宁测试之前设置意图存根:

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

如果您需要验证来自另一个应用程序(如 phone 拨号器)的实际用户输入,这超出了 Espresso 的范围。由于我目前与一家帮助处理此类案例的供应商合作,因此我不愿命名名称和工具,但很多人确实需要编写模拟真实端到端体验的测试。

Mike Evans 写了一篇关于测试意图的精彩文章here and there's always the android documentation here