Espresso-Intents
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
Espresso-Intents는 Espresso의 확장 프로그램이며, 테스트 중인 애플리케이션에서 전송된 인텐트의 유효성 검사 및 스텁을 가능하게 합니다.
Mockito와 유사하지만 Android 인텐트에 사용됩니다.
앱이 다른 앱 또는 플랫폼에 기능을 위임하면 다른 앱 또는 플랫폼이 올바르게 작동한다고 가정하고 Espresso-Intents를 사용하여 자체 앱 로직에 집중할 수 있습니다. Espresso-Intents를 사용하면 발신 인텐트를 일치시키고 유효성 검사하거나 실제 인텐트 응답 대신 스터브 응답을 제공할 수도 있습니다.
프로젝트에 Espresso-Intents 포함
앱의 app/build.gradle
파일에서 dependencies
내에 다음 행을 추가합니다.
Groovy
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.6.1'
Kotlin
androidTestImplementation('androidx.test.espresso:espresso-intents:3.6.1')
Espresso-Intents는 Espresso 2.1 이상 및 버전 0.3 이상의 Android 테스트 라이브러리와만 호환되므로 그러한 행도 업데이트해야 합니다.
Groovy
androidTestImplementation 'androidx.test:runner:1.6.1'
androidTestImplementation 'androidx.test:rules:1.6.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1'
Kotlin
androidTestImplementation('androidx.test:runner:1.6.1')
androidTestImplementation('androidx.test:rules:1.6.1')
androidTestImplementation('androidx.test.espresso:espresso-core:3.6.1')
테스트 규칙 작성
Espresso-Intents 테스트를 작성하기 전에 IntentsTestRule
을 설정합니다. 이는 ActivityTestRule
클래스의 확장이며 기능적 UI 테스트에서 Espresso-Intents API를 쉽게 사용할 수 있도록 합니다. IntentsTestRule
은 @Test
주석이 달린 각 테스트 전에 Espresso-Intents를 초기화하고 각 테스트 실행 후 Espresso-Intents를 해제합니다.
다음 코드 스니펫은 IntentsTestRule
의 예입니다.
Kotlin
@get:Rule
val intentsTestRule = IntentsTestRule(MyActivity::class.java)
자바
@Rule
public IntentsTestRule<MyActivity> intentsTestRule =
new IntentsTestRule<>(MyActivity.class);
일치
Espresso-Intents는 Hamcrest 매처를 사용하여 정의된 특정 일치 기준에 따라 발신 인텐트를 가로챌 수 있는 기능을 제공합니다. Hamcrest를 사용하면 다음 작업이 가능합니다.
- 기존 인텐트 매처 사용: 거의 모든 경우에 선호되는 가장 쉬운 옵션입니다.
- 자체 인텐트 매처 구현: 가장 유연한 옵션입니다. 자세한 내용은 Hamcrest 가이드 내의 '맞춤 매처 작성'이라는 섹션에 있습니다.
Espresso-Intents는 인텐트 유효성 검사 및 스터브를 위해 각각 intended()
및 intending()
메서드를 제공합니다. 두 메서드 모두 Hamcrest Matcher<Intent>
객체를 인수로 사용합니다.
다음 코드 스니펫은 기존 인텐트 매처를 사용하는 인텐트 유효성 검사를 보여줍니다. 이 인텐트 매처는 브라우저를 시작하는 발신 인텐트를 일치시킵니다.
Kotlin
assertThat(intent).hasAction(Intent.ACTION_VIEW)
assertThat(intent).categories().containsExactly(Intent.CATEGORY_BROWSABLE)
assertThat(intent).hasData(Uri.parse("www.google.com"))
assertThat(intent).extras().containsKey("key1")
assertThat(intent).extras().string("key1").isEqualTo("value1")
assertThat(intent).extras().containsKey("key2")
assertThat(intent).extras().string("key2").isEqualTo("value2")
자바
assertThat(intent).hasAction(Intent.ACTION_VIEW);
assertThat(intent).categories().containsExactly(Intent.CATEGORY_BROWSABLE);
assertThat(intent).hasData(Uri.parse("www.google.com"));
assertThat(intent).extras().containsKey("key1");
assertThat(intent).extras().string("key1").isEqualTo("value1");
assertThat(intent).extras().containsKey("key2");
assertThat(intent).extras().string("key2").isEqualTo("value2");
인텐트 유효성 검사
Espresso-Intents는 테스트 중인 애플리케이션에서 활동을 시작하려는 모든 인텐트를 기록합니다. Mockito.verify()
과 유사한 intended()
메서드를 사용하여 지정된 인텐트가 표시되었는지 어설션할 수 있습니다. 하지만 이렇게 하도록 명시적으로 구성하지 않으면 Espresso-Intents는 인텐트에 관한 응답을 스터브하지 않습니다.
다음 코드 스니펫은 외부 '휴대전화' 활동을 시작하는 발신 인텐트의 유효성을 검사하지만 이 인텐트에 관한 응답을 스터브하지 않는 예제 테스트입니다.
Kotlin
@Test fun 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"))
}
자바
@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"));
}
스터브
Mockito.when()
과 유사한 intending()
메서드를 사용하여 startActivityForResult()
로 시작된 활동에 관한 스터브 응답을 제공할 수 있습니다. 외부 활동의 사용자 인터페이스를 조작할 수 없고 테스트 중인 활동에 반환되는 ActivityResult
를 제어할 수 없으므로 이 메서드는 외부 활동에 특히 유용합니다.
다음 코드 스니펫은 사용자가 테스트 중인 앱에서 '연락처' 활동을 시작할 때 연락처 전화번호가 표시되는지 확인하는 activityResult_DisplaysContactsPhoneNumber()
테스트 예를 구현합니다.
특정 활동이 시작될 때 반환할 결과를 빌드합니다. 테스트 예에서는 '연락처'로 전송된 모든 인텐트를 가로채고 결과 코드 RESULT_OK
를 사용하여 유효한 ActivityResult
로 응답을 스터브합니다.
Kotlin
val resultData = Intent()
val phoneNumber = "123-345-6789"
resultData.putExtra("phone", phoneNumber)
val result = Instrumentation.ActivityResult(Activity.RESULT_OK, resultData)
자바
Intent resultData = new Intent();
String phoneNumber = "123-345-6789";
resultData.putExtra("phone", phoneNumber);
ActivityResult result =
new ActivityResult(Activity.RESULT_OK, resultData);
Espresso에 '연락처' 인텐트의 모든 호출에 관한 응답으로 스텁 결과 객체를 제공하도록 지시합니다.
Kotlin
intending(toPackage("com.android.contacts")).respondWith(result)
자바
intending(toPackage("com.android.contacts")).respondWith(result);
활동을 시작하는 데 사용된 작업이 예상 스텁 결과를 생성하는지 확인합니다. 이 경우 예제 테스트에서 '연락처 활동'이 시작될 때 전화번호 '123-345-6789'가 반환되고 표시되는지 확인합니다.
Kotlin
onView(withId(R.id.pickButton)).perform(click())
onView(withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)))
자바
onView(withId(R.id.pickButton)).perform(click());
onView(withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)));
다음은 전체 activityResult_DisplaysContactsPhoneNumber()
테스트입니다.
Kotlin
@Test fun activityResult_DisplaysContactsPhoneNumber() {
// Build the result to return when the activity is launched.
val resultData = Intent()
val phoneNumber = "123-345-6789"
resultData.putExtra("phone", phoneNumber)
val result = Instrumentation.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)))
}
Java
@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)));
}
추가 리소스
Android 테스트에서 Espresso-Intents를 사용하는 방법에 관한 자세한 내용은 다음 자료를 참고하세요.
샘플
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-08-08(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["필요한 정보가 없음","missingTheInformationINeed","thumb-down"],["너무 복잡함/단계 수가 너무 많음","tooComplicatedTooManySteps","thumb-down"],["오래됨","outOfDate","thumb-down"],["번역 문제","translationIssue","thumb-down"],["샘플/코드 문제","samplesCodeIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-08-08(UTC)"],[],[],null,["# Espresso-Intents is an extension to Espresso, which enables validation and\nstubbing of [intents](/reference/android/content/Intent) sent out by the\napplication under test. It's like [Mockito](http://site.mockito.org), but for Android Intents.\n\nIf your app delegates functionality to other apps or the platform, you can use\nEspresso-Intents to focus on your own app's logic while assuming that other apps\nor the platform will function correctly. With Espresso-Intents, you can match\nand validate your outgoing intents or even provide stub responses in place of\nactual intent responses.\n\nInclude Espresso-Intents in your project\n----------------------------------------\n\nIn your app's `app/build.gradle` file, add the following line inside\n`dependencies`: \n\n### Groovy\n\n```groovy\nandroidTestImplementation 'androidx.test.espresso:espresso-intents:3.6.1'\n```\n\n### Kotlin\n\n```kotlin\nandroidTestImplementation('androidx.test.espresso:espresso-intents:3.6.1')\n```\n\nEspresso-Intents is only compatible with Espresso 2.1+ and version 0.3+ of\nAndroid testing libraries, so make sure you update those lines as well: \n\n### Groovy\n\n```groovy\nandroidTestImplementation 'androidx.test:runner:1.6.1'\nandroidTestImplementation 'androidx.test:rules:1.6.1'\nandroidTestImplementation 'androidx.test.espresso:espresso-core:3.6.1'\n```\n\n### Kotlin\n\n```kotlin\nandroidTestImplementation('androidx.test:runner:1.6.1')\nandroidTestImplementation('androidx.test:rules:1.6.1')\nandroidTestImplementation('androidx.test.espresso:espresso-core:3.6.1')\n```\n\nWrite test rules\n----------------\n\nBefore writing an Espresso-Intents test, set up an `IntentsTestRule`. This is an\nextension of the class `ActivityTestRule` and makes it easy to use\nEspresso-Intents APIs in functional UI tests. An `IntentsTestRule` initializes\nEspresso-Intents before each test annotated with `@Test` and releases\nEspresso-Intents after each test run.\n\nThe following code snippet is an example of an `IntentsTestRule`: \n\n### Kotlin\n\n```kotlin\n@get:Rule\nval intentsTestRule = IntentsTestRule(MyActivity::class.java)\n```\n\n### Java\n\n```java\n@Rule\npublic IntentsTestRule\u003cMyActivity\u003e intentsTestRule =\n new IntentsTestRule\u003c\u003e(MyActivity.class);\n```\n\nMatch\n-----\n\nEspresso-Intents provides the ability to intercept outgoing intents based on\ncertain matching criteria, which are defined using Hamcrest Matchers. Hamcrest\nallows you to:\n\n- **Use an existing intent matcher:** Easiest option, which should almost always be preferred.\n- **Implement your own intent matcher:** Most flexible option. More details are available in the section entitled \"Writing custom matchers\" within the [Hamcrest tutorial](https://code.google.com/archive/p/hamcrest/wikis/Tutorial.wiki).\n\nEspresso-Intents offers the [`intended()`](/reference/androidx/test/espresso/intent/Intents#intended(org.hamcrest.Matcher%3Candroid.content.Intent%3E,%20androidx.test.espresso.intent.VerificationMode))\nand [`intending()`](/reference/androidx/test/espresso/intent/Intents#intending(org.hamcrest.Matcher%3Candroid.content.Intent%3E)) methods for intent validation and\nstubbing, respectively. Both take a Hamcrest `Matcher\u003cIntent\u003e` object as an\nargument.\n\nThe following code snippet shows intent validation that uses existing intent\nmatchers that matches an outgoing intent that starts a browser: \n\n### Kotlin\n\n```kotlin\nassertThat(intent).hasAction(Intent.ACTION_VIEW)\nassertThat(intent).categories().containsExactly(Intent.CATEGORY_BROWSABLE)\nassertThat(intent).hasData(Uri.parse(\"www.google.com\"))\nassertThat(intent).extras().containsKey(\"key1\")\nassertThat(intent).extras().string(\"key1\").isEqualTo(\"value1\")\nassertThat(intent).extras().containsKey(\"key2\")\nassertThat(intent).extras().string(\"key2\").isEqualTo(\"value2\")\n```\n\n### Java\n\n```java\nassertThat(intent).hasAction(Intent.ACTION_VIEW);\nassertThat(intent).categories().containsExactly(Intent.CATEGORY_BROWSABLE);\nassertThat(intent).hasData(Uri.parse(\"www.google.com\"));\nassertThat(intent).extras().containsKey(\"key1\");\nassertThat(intent).extras().string(\"key1\").isEqualTo(\"value1\");\nassertThat(intent).extras().containsKey(\"key2\");\nassertThat(intent).extras().string(\"key2\").isEqualTo(\"value2\");\n```\n\nValidate intents\n----------------\n\nEspresso-Intents records all intents that attempt to launch activities from the\napplication under test. Using the `intended()` method, which is similar to\n`Mockito.verify()`, you can assert that a given intent has been seen. However,\nEspresso-Intents doesn't stub out responses to intents unless you [explicitly configure](#stubbing)\nit to do so.\n\nThe following code snippet is an example test that validates, but doesn't stub\nout responses to, an outgoing intent that launches an external \"phone\" activity: \n\n### Kotlin\n\n```kotlin\n@Test fun validateIntentSentToPackage() {\n // User action that results in an external \"phone\" activity being launched.\n user.clickOnView(system.getView(R.id.callButton))\n\n // Using a canned RecordedIntentMatcher to validate that an intent resolving\n // to the \"phone\" activity has been sent.\n intended(toPackage(\"com.android.phone\"))\n}\n```\n\n### Java\n\n```java\n@Test\npublic void validateIntentSentToPackage() {\n // User action that results in an external \"phone\" activity being launched.\n user.clickOnView(system.getView(R.id.callButton));\n\n // Using a canned RecordedIntentMatcher to validate that an intent resolving\n // to the \"phone\" activity has been sent.\n intended(toPackage(\"com.android.phone\"));\n}\n```\n\nStubbing\n--------\n\nUsing the `intending()` method, which is similar to `Mockito.when()`, you can\nprovide a stub response for activities that are launched with\n`startActivityForResult()`. This is particularly useful for external activities\nbecause you cannot manipulate the user interface of an external activity nor\ncontrol the `ActivityResult` returned to the activity under test.\n\nThe following code snippets implement an example\n`activityResult_DisplaysContactsPhoneNumber()` test, which verifies that when a\nuser launches a \"contact\" activity in the app under test, the contact phone\nnumber is displayed:\n\n1. Build the result to return when a particular activity is launched. The\n example test intercepts all Intents sent to \"contacts\" and stubs out their\n responses with a valid `ActivityResult`, using the result code\n `RESULT_OK`\n\n ### Kotlin\n\n ```kotlin\n val resultData = Intent()\n val phoneNumber = \"123-345-6789\"\n resultData.putExtra(\"phone\", phoneNumber)\n val result = Instrumentation.ActivityResult(Activity.RESULT_OK, resultData)\n ```\n\n ### Java\n\n ```java\n Intent resultData = new Intent();\n String phoneNumber = \"123-345-6789\";\n resultData.putExtra(\"phone\", phoneNumber);\n ActivityResult result =\n new ActivityResult(Activity.RESULT_OK, resultData);\n ```\n2. Instruct Espresso to provide the stub result object in response to all\n invocations of the \"contacts\" intent:\n\n ### Kotlin\n\n ```kotlin\n intending(toPackage(\"com.android.contacts\")).respondWith(result)\n ```\n\n ### Java\n\n ```java\n intending(toPackage(\"com.android.contacts\")).respondWith(result);\n ```\n3. Verify that the action used to launch the activity produces the expected\n stub result. In this case, the example test checks that the phone number\n \"123-345-6789\" is returned and\n displayed when the \"contacts activity\" is launched:\n\n ### Kotlin\n\n ```kotlin\n onView(withId(R.id.pickButton)).perform(click())\n onView(withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)))\n ```\n\n ### Java\n\n ```java\n onView(withId(R.id.pickButton)).perform(click());\n onView(withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)));\n ```\n\nHere is the complete `activityResult_DisplaysContactsPhoneNumber()` test: \n\n### Kotlin\n\n```kotlin\n@Test fun activityResult_DisplaysContactsPhoneNumber() {\n // Build the result to return when the activity is launched.\n val resultData = Intent()\n val phoneNumber = \"123-345-6789\"\n resultData.putExtra(\"phone\", phoneNumber)\n val result = Instrumentation.ActivityResult(Activity.RESULT_OK, resultData)\n\n // Set up result stubbing when an intent sent to \"contacts\" is seen.\n intending(toPackage(\"com.android.contacts\")).respondWith(result)\n\n // User action that results in \"contacts\" activity being launched.\n // Launching activity expects phoneNumber to be returned and displayed.\n onView(withId(R.id.pickButton)).perform(click())\n\n // Assert that the data we set up above is shown.\n onView(withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)))\n}\n```\n\n### Java\n\n```java\n@Test\npublic void activityResult_DisplaysContactsPhoneNumber() {\n // Build the result to return when the activity is launched.\n Intent resultData = new Intent();\n String phoneNumber = \"123-345-6789\";\n resultData.putExtra(\"phone\", phoneNumber);\n ActivityResult result =\n new ActivityResult(Activity.RESULT_OK, resultData);\n\n // Set up result stubbing when an intent sent to \"contacts\" is seen.\n intending(toPackage(\"com.android.contacts\")).respondWith(result);\n\n // User action that results in \"contacts\" activity being launched.\n // Launching activity expects phoneNumber to be returned and displayed.\n onView(withId(R.id.pickButton)).perform(click());\n\n // Assert that the data we set up above is shown.\n onView(withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)));\n}\n```\n\nAdditional resources\n--------------------\n\nFor more information about using Espresso-Intents in Android tests, consult\nthe following resources.\n\n### Samples\n\n- [IntentsBasicSample](https://github.com/android/testing-samples/tree/main/ui/espresso/IntentsBasicSample): Basic usage of `intended()` and `intending()`.\n- [IntentsAdvancedSample](https://github.com/android/testing-samples/tree/main/ui/espresso/IntentsAdvancedSample): Simulates a user fetching a bitmap using the camera."]]