Espresso 意圖
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
Espresso-Intents 是 Espresso 的擴充功能,可驗證及擷取受測應用程式傳送的意圖。這就像是 Android Intent 專用的
Mockito。
如果應用程式會將功能委派給其他應用程式或平台,您可以使用 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 以上版本和 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
類別的擴充功能,可讓您在功能性 UI 測試中輕鬆使用 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 比對器定義。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")
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");
驗證意圖
Espresso-Intents 會記錄所有嘗試從受測應用程式啟動活動的意圖。使用 intended()
方法 (類似於 Mockito.verify()
),即可判斷是否已看到特定意圖。不過,除非您明確設定,否則 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"))
}
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"));
}
Stubbing
使用類似 Mockito.when()
的 intending()
方法,您可以為透過 startActivityForResult()
啟動的活動提供虛設常式回應。這對外部活動特別有用,因為您無法操控外部活動的使用者介面,也無法控制傳回受測活動的 ActivityResult
。
下列程式碼片段會實作 activityResult_DisplaysContactsPhoneNumber()
測試範例,驗證使用者在受測應用程式中啟動「聯絡人」活動時,是否會顯示聯絡人電話號碼:
建構在啟動特定活動時傳回的結果。範例測試會攔截傳送至「contacts」的所有意圖,並使用結果代碼 RESULT_OK
,以有效的 ActivityResult
存根化其回應。
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」意圖的叫用:
Kotlin
intending(toPackage("com.android.contacts")).respondWith(result)
Java
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)))
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 和/或其關係企業的商標或註冊商標。
上次更新時間: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"]],["上次更新時間: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."]]