使用浓缩咖啡进行测试



如何使用浓缩咖啡为以下代码编写测试用例。我有以下代码,单击图标时会执行。 我知道我可以使用 intended(toPackage(....并且可能会嘲笑通过启动启动的意图的结果 活动结果 但是如何处理这种情况。

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

答案是在测试代码之后使用"预期"方法来验证活动结果是否满足您的要求。它看起来像这样:

@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在这里写了一篇关于测试意图的文章,这里总是有Android文档。

最新更新