Espresso-Intents
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
Espresso-Intents 是 Espresso 的扩展程序,支持对被测应用发出的 intent 进行验证和打桩。它与
Mockito 类似,但适用于 Android Intent。
如果您的应用将功能委托给其他应用或平台,您可以使用 Espresso-Intents 以专注于自己应用的逻辑,同时假定其他应用或平台能够正常运行。借助 Espresso-Intents,您可以匹配和验证您的传出 intent,甚至可以提供桩响应来代替实际的 intent 响应。
在项目中添加 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 及更高版本以及 Android 测试库 0.3 及更高版本兼容,因此请务必也更新以下代码行:
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
类的扩展程序,可让您在功能界面测试中轻松使用 Espresso-Intents API。IntentsTestRule
会在每个带有 @Test
注释的测试运行前初始化 Espresso-Intents,并在每个测试运行后释放 Espresso-Intents。
以下代码段是 IntentsTestRule
的一个示例:
Kotlin
@get:Rule
val intentsTestRule = IntentsTestRule(MyActivity::class.java)
Java
@Rule
public IntentsTestRule<MyActivity> intentsTestRule =
new IntentsTestRule<>(MyActivity.class);
匹配
Espresso-Intents 能够根据使用 Hamcrest 匹配器定义的某些匹配条件来拦截传出 intent。Hamcrest 可让您:
- 使用现有的 intent 匹配器:这是最简单的选项,应该几乎总是首选。
- 实现您自己的 intent 匹配器:这是最灵活的选项。如需了解详情,请参阅 Hamcrest 教程中标题为“编写自定义匹配器”的部分。
Espresso-Intents 分别为 intent 验证和打桩提供了 intended()
和 intending()
方法。两者均以 Hamcrst Matcher<Intent>
对象作为参数。
以下代码段展示了 intent 验证,使用的是现有 intent 匹配器,匹配启动浏览器的传出 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")
Java
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");
验证 intent
Espresso-Intents 会记录尝试从被测应用启动 activity 的所有 intent。使用 intended()
方法(类似于 Mockito.verify()
),您可以断言已看到的给定 intent。不过,Espresso-Intents 不会对 intent 的响应打桩,除非您进行了明确配置以要求它这样做。
以下代码段是一个示例测试,该测试验证用来启动外部“phone”Activity 的传出 intent 的响应,但不对其进行打桩:
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"))
}
Java
@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"));
}
打桩
使用 intending()
方法(类似于 Mockito.when()
),您可以为使用 startActivityForResult()
启动的 activity 提供桩响应。这对于外部 activity 特别有用,因为您无法操纵外部 activity 的界面,也无法控制返回给被测 activity 的 ActivityResult
。
以下代码段实现了一个示例 activityResult_DisplaysContactsPhoneNumber()
测试,该测试验证当用户在被测应用中启动“contacts”Activity 时,是否会显示相应的联系人电话号码:
构建要在启动特定 Activity 时返回的结果。该示例测试会拦截发送到“contacts”的所有 intent 并使用有效的 ActivityResult
对其响应进行打桩(使用结果代码 RESULT_OK
):
Kotlin
val resultData = Intent()
val phoneNumber = "123-345-6789"
resultData.putExtra("phone", phoneNumber)
val result = Instrumentation.ActivityResult(Activity.RESULT_OK, resultData)
Java
Intent resultData = new Intent();
String phoneNumber = "123-345-6789";
resultData.putExtra("phone", phoneNumber);
ActivityResult result =
new ActivityResult(Activity.RESULT_OK, resultData);
指示 Espresso 提供桩结果对象来响应“contacts”intent 的所有调用:
Kotlin
intending(toPackage("com.android.contacts")).respondWith(result)
Java
intending(toPackage("com.android.contacts")).respondWith(result);
验证用于启动该 activity 的操作是否产生了预期的桩结果。在本例中,该示例测试会检查当启动“contacts”Activity 时是否返回并显示了电话号码“123-345-6789”:
Kotlin
onView(withId(R.id.pickButton)).perform(click())
onView(withId(R.id.phoneNumber)).check(matches(withText(phoneNumber)))
Java
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,请参阅以下资源。
示例
本页面上的内容和代码示例受内容许可部分所述许可的限制。Java 和 OpenJDK 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):2025-08-08。
[[["易于理解","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"]],["最后更新时间 (UTC):2025-08-08。"],[],[],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."]]