콘텐츠로 건너뛰기

자주 방문한 페이지

최근 방문한 페이지

navigation

Espresso-Intents

Espresso-Intents is an extension to Espresso, which enables validation and stubbing of intents sent out by the application under test. It’s like Mockito, but for Android Intents.

If your app delegates functionality to other apps or the platform, you can use Espresso-Intents to focus on your own app's logic while assuming that other apps or the platform will function correctly. With Espresso-Intents, you can match and validate your outgoing intents or even provide stub responses in place of actual intent responses.

Downloading Espresso-Intents

Make sure you have installed the Android Support Repository.

Open your app’s build.gradle file. This is usually not the top-level build.gradle file but app/build.gradle. Add the following line inside dependencies:

androidTestCompile 'com.android.support.test.espresso:espresso-intents:3.0.1'

Espresso-Intents is only compatible with Espresso 2.1+ and the testing support library 0.3+ so make sure you update those lines as well:

androidTestCompile 'com.android.support.test:runner:1.0.1'
androidTestCompile 'com.android.support.test:rules:1.0.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:3.0.1'

Writing test rules

Before writing an Espresso-Intents test, set up an IntentsTestRule. This is an extension of the class ActivityTestRule and makes it easy to use Espresso-Intents APIs in functional UI tests. An IntentsTestRule initializes Espresso-Intents before each test annotated with @Test and releases Espresso-Intents after each test run.

The following code snippet is an example of an IntentsTestRule:

@Rule
public IntentsTestRule<MyActivity> intentsTestRule =
    new IntentsTestRule<>(MyActivity.class);

Matching

Espresso-Intents provides the ability to intercept outgoing intents based on certain matching criteria, which are defined using Hamcrest Matchers. Hamcrest allows you to:

Espresso-Intents offers the intended() and intending() methods for intent validation and stubbing, respectively. Both take a Hamcrest Matcher<Intent> object as an argument.

The following code snippet shows intent validation that uses existing intent matchers that matches an outgoing intent that starts a browser:

intended(allOf(
    hasAction(equalTo(Intent.ACTION_VIEW)),
    hasCategories(hasItem(equalTo(Intent.CATEGORY_BROWSABLE))),
    hasData(hasHost(equalTo("www.google.com"))),
    hasExtras(allOf(
        hasEntry(equalTo("key1"), equalTo("value1")),
        hasEntry(equalTo("key2"), equalTo("value2")))),
        toPackage("com.android.browser")));

Validating intents

Espresso-Intents records all intents that attempt to launch activities from the application under test. Using the intended() method, which is similar to Mockito.verify(), you can assert that a given intent has been seen. However, Espresso-Intents doesn't stub out responses to intents unless you explicitly configure it to do so.

The following code snippet is an example test that validates, but doesn't stub out responses to, an outgoing intent that launches an external "phone" activity:

@Test
public void validateIntentSentToPackage() {
    // User action that results in an external "phone" activity being launched.
    user.clickOnView(system.getView(R.id.callButton));

    // Using a canned RecordedIntentMatcher to validate that an intent resolving
    // to the "phone" activity has been sent.
    intended(toPackage("com.android.phone"));
}

Stubbing

Using the intending() method, which is similar to Mockito.when(), you can provide a stub response for activities that are launched with startActivityForResult(). This is particularly useful for external activities because you cannot manipulate the user interface of an external activity nor control the ActivityResult returned to the activity under test.

The following code snippets implement an example activityResult_DisplaysContactsPhoneNumber() test, which verifies that when a user launches a "contact" activity in the app under test, the contact phone number is displayed:

  1. Build the result to return when a particular activity is launched. The example test intercepts all Intents sent to "contacts" and stubs out their responses with a valid ActivityResult, using the result code RESULT_OK:

    Intent resultData = new Intent();
    String phoneNumber = "123-345-6789";
    resultData.putExtra("phone", phoneNumber);
    ActivityResult result =
        new ActivityResult(Activity.RESULT_OK, resultData);
    
  2. Instruct Espresso to provide the stub result object in response to all invocations of the "contacts" intent:

    intending(toPackage("com.android.contacts")).respondWith(result);
    
  3. Verify that the action used to launch the activity produces the expected stub result. In this case, the example test checks that the phone number "123-345-6789" is returned and displayed when the "contacts activity" is launched:

    onView(withId(R.id.pickButton)).perform(click());
    onView(withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)));
    

Here is the complete activityResult_DisplaysContactsPhoneNumber() test:

@Test
public void activityResult_DisplaysContactsPhoneNumber() {
    // Build the result to return when the activity is launched.
    Intent resultData = new Intent();
    String phoneNumber = "123-345-6789";
    resultData.putExtra("phone", phoneNumber);
    ActivityResult result =
        new ActivityResult(Activity.RESULT_OK, resultData);

    // Set up result stubbing when an intent sent to "contacts" is seen.
    intending(toPackage("com.android.contacts")).respondWith(result);

    // User action that results in "contacts" activity being launched.
    // Launching activity expects phoneNumber to be returned and displayed.
    onView(withId(R.id.pickButton)).perform(click());

    // Assert that the data we set up above is shown.
    onView(withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)));
}
이 사이트는 쿠키를 사용하여 사이트별 언어 및 표시 옵션에 대한 환경설정을 저장합니다.

Google Play에서 성공을 거두는 데 도움이 되는 최신 Android 개발자 뉴스 및 도움말을 받아 보세요.

* 필수 입력란

완료되었습니다.

WeChat에서 Google Developers 팔로우하기

이 사이트를 (으)로 탐색할까요?

페이지를 요청했지만 이 사이트의 언어 환경설정은 입니다.

언어 환경설정을 변경하고 이 사이트를 (으)로 탐색할까요? 언어 환경설정을 나중에 변경하려면 각 페이지 하단의 언어 메뉴를 사용하세요.

이 클래스를 사용하려면 API 수준 이상이 필요합니다.

문서에 대해 선택한 API 수준이 이므로 이 문서가 표시되지 않습니다. 왼쪽 탐색 메뉴의 선택기로 문서 API 수준을 변경할 수 있습니다.

앱에 필요한 API 수준 지정에 관한 자세한 내용은 다양한 플랫폼 버전 지원을 참조하세요.

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)