使用 Espresso Device API 測試螢幕設定變更
透過集合功能整理內容
你可以依據偏好儲存及分類內容。
當裝置發生常見的設定變更 (例如旋轉和展開螢幕) 時,請使用 Espresso Device API 測試應用程式。Espresso 裝置 API 可讓您在虛擬裝置上模擬這些設定變更,並同步執行測試,因此一次只會發生一個 UI 動作或斷言,測試結果也更可靠。如果您不熟悉如何使用 Espresso 編寫 UI 測試,請參閱相關說明文件。
如要使用 Espresso 裝置 API,您需要:
- Android Studio Iguana 以上版本
- Android Gradle 外掛程式 8.3 以上版本
- Android Emulator 33.1.10 以上版本
- 搭載 API 級別 24 以上版本的 Android 虛擬裝置
設定 Espresso 裝置 API 的專案
如要設定專案,使其支援 Espresso 裝置 API,請按照下列步驟操作:
如要讓測試將指令傳送至測試裝置,請在 androidTest
來源集的資訊清單檔案中,加入 INTERNET
和 ACCESS_NETWORK_STATE
權限:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
在 gradle.properties
檔案中啟用 enableEmulatorControl
實驗旗標:
android.experimental.androidTest.enableEmulatorControl=true
在模組層級的建構指令碼中啟用 emulatorControl
選項:
Kotlin
testOptions {
emulatorControl {
enable = true
}
}
Groovy
testOptions {
emulatorControl {
enable = true
}
}
在模組層級的建構指令碼中,將 Espresso 裝置程式庫匯入專案:
Kotlin
dependencies {
androidTestImplementation("androidx.test.espresso:espresso-device:1.0.1")
}
Groovy
dependencies {
androidTestImplementation 'androidx.test.espresso:espresso-device:1.0.1'
}
針對常見的設定變更進行測試
Espresso 裝置 API 提供多種螢幕方向和折疊狀態,可用於模擬裝置設定變更。
針對螢幕旋轉進行測試
以下範例說明如何測試裝置螢幕旋轉時,應用程式的行為:
首先,為了確保起始狀態一致,請將裝置設為直向模式:
import androidx.test.espresso.device.action.ScreenOrientation
import androidx.test.espresso.device.rules.ScreenOrientationRule
...
@get:Rule
val screenOrientationRule: ScreenOrientationRule = ScreenOrientationRule(ScreenOrientation.PORTRAIT)
建立測試,在測試執行期間將裝置設為橫向模式:
@Test
fun myRotationTest() {
...
// Sets the device to landscape orientation during test execution.
onDevice().setScreenOrientation(ScreenOrientation.LANDSCAPE)
...
}
螢幕旋轉後,請確認 UI 是否如預期調整為新版面配置。
@Test
fun myRotationTest() {
...
// Sets the device to landscape orientation during test execution.
onDevice().setScreenOrientation(ScreenOrientation.LANDSCAPE)
composeTestRule.onNodeWithTag("NavRail").assertIsDisplayed()
composeTestRule.onNodeWithTag("BottomBar").assertDoesNotExist()
}
測試螢幕展開功能
以下範例說明如何測試應用程式在摺疊式裝置上展開螢幕時的行為:
首先,請呼叫 onDevice().setClosedMode()
,在裝置摺疊狀態下進行測試。確認應用程式版面配置可配合緊湊型螢幕寬度調整。
@Test
fun myUnfoldedTest() {
onDevice().setClosedMode()
composeTestRule.onNodeWithTag("BottomBar").assetIsDisplayed()
composeTestRule.onNodeWithTag("NavRail").assetDoesNotExist()
...
}
如要轉換至完全展開狀態,請呼叫 onDevice().setFlatMode()
。確認應用程式的版面配置可配合擴大版大小類別調整。
@Test
fun myUnfoldedTest() {
onDevice().setClosedMode()
...
onDevice().setFlatMode()
composeTestRule.onNodeWithTag("NavRail").assertIsDisplayed()
composeTestRule.onNodeWithTag("BottomBar").assetDoesNotExist()
}
指定測試所需的裝置
如果您在非摺疊式裝置上執行會執行摺疊動作的測試,測試可能會失敗。如要只執行與執行裝置相關的測試,請使用 @RequiresDeviceMode
註解。測試執行器會自動略過在不支援所測試設定的裝置上執行測試。您可以將裝置規定規則新增至各項測試或整個測試類別。
舉例來說,如要指定測試只能在支援展開至平坦設定的裝置上執行,請在測試中新增下列 @RequiresDeviceMode
程式碼:
@Test
@RequiresDeviceMode(mode = FLAT)
fun myUnfoldedTest() {
...
}
這個頁面中的內容和程式碼範例均受《內容授權》中的授權所規範。Java 與 OpenJDK 是 Oracle 和/或其關係企業的商標或註冊商標。
上次更新時間:2025-09-04 (世界標準時間)。
[[["容易理解","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-09-04 (世界標準時間)。"],[],[],null,["Use the Espresso Device API to test your app when the device undergoes common\nconfiguration changes, such as rotation and screen unfolding. The Espresso\nDevice API lets you simulate these configuration changes on a virtual device and\nexecutes your tests synchronously, so only one UI action or assertion happens at\na time and your test results are more reliable. If you're new to writing UI\ntests with Espresso, see its [documentation](/training/testing/espresso).\n\nTo use the Espresso Device API, you need the following:\n\n- Android Studio Iguana or higher\n- Android Gradle plugin 8.3 or higher\n- Android Emulator 33.1.10 or higher\n- Android virtual device that runs API level 24 or higher\n\nSet up your project for the Espresso Device API\n\nTo set up your project so it supports the Espresso Device API, do the following:\n\n1. To let the test pass commands to the test device, add the\n `INTERNET` and `ACCESS_NETWORK_STATE` permissions to the manifest file in the `androidTest` source set:\n\n ```\n \u003cuses-permission android:name=\"android.permission.INTERNET\" /\u003e\n \u003cuses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" /\u003e\n \n ```\n2. Enable the `enableEmulatorControl` experimental flag in the\n `gradle.properties` file:\n\n ```\n android.experimental.androidTest.enableEmulatorControl=true\n \n ```\n3. Enable the `emulatorControl` option in the module-level build\n script:\n\n Kotlin \n\n ```kotlin\n testOptions {\n emulatorControl {\n enable = true\n }\n }\n \n ```\n\n Groovy \n\n ```groovy\n testOptions {\n emulatorControl {\n enable = true\n }\n }\n \n ```\n4. In the module-level build script, import the Espresso Device library\n into your project:\n\n Kotlin \n\n ```kotlin\n dependencies {\n androidTestImplementation(\"androidx.test.espresso:espresso-device:1.0.1\")\n }\n \n ```\n\n Groovy \n\n ```groovy\n dependencies {\n androidTestImplementation 'androidx.test.espresso:espresso-device:1.0.1'\n }\n \n ```\n\nTest against common configuration changes\n\nThe Espresso Device API has multiple screen orientation and foldable states that\nyou can use to simulate device configuration changes.\n\nTest against screen rotation\n\nHere's an example of how to test what happens to your app when the device screen\nrotates:\n\n1. First, for a consistent starting state set the device to portrait\n mode:\n\n ```kotlin\n import androidx.test.espresso.device.action.ScreenOrientation\n import androidx.test.espresso.device.rules.ScreenOrientationRule\n ...\n @get:Rule\n val screenOrientationRule: ScreenOrientationRule = ScreenOrientationRule(ScreenOrientation.PORTRAIT)\n \n ```\n2. Create a test that sets the device to landscape orientation during test\n execution:\n\n ```kotlin\n @Test\n fun myRotationTest() {\n ...\n // Sets the device to landscape orientation during test execution.\n onDevice().setScreenOrientation(ScreenOrientation.LANDSCAPE)\n ...\n }\n \n ```\n3. After the screen rotates, check that the UI adapts to the new layout as expected.\n\n ```kotlin\n @Test\n fun myRotationTest() {\n ...\n // Sets the device to landscape orientation during test execution.\n onDevice().setScreenOrientation(ScreenOrientation.LANDSCAPE)\n composeTestRule.onNodeWithTag(\"NavRail\").assertIsDisplayed()\n composeTestRule.onNodeWithTag(\"BottomBar\").assertDoesNotExist()\n }\n \n ```\n\nTest against screen unfolding\n\nHere's an example of how to test what happens to your app if it's on a foldable\ndevice and the screen unfolds:\n\n1. First, test with the device in the folded state by calling\n `onDevice().setClosedMode()`. Make sure that your app's layout\n adapts to the compact screen width.\n\n ```kotlin\n @Test\n fun myUnfoldedTest() {\n onDevice().setClosedMode()\n composeTestRule.onNodeWithTag(\"BottomBar\").assetIsDisplayed()\n composeTestRule.onNodeWithTag(\"NavRail\").assetDoesNotExist()\n ...\n }\n \n ```\n2. To transition to a fully unfolded state, call\n `onDevice().setFlatMode()`. Check that the app's layout adapts to\n the expanded size class.\n\n ```kotlin\n @Test\n fun myUnfoldedTest() {\n onDevice().setClosedMode()\n ...\n onDevice().setFlatMode()\n composeTestRule.onNodeWithTag(\"NavRail\").assertIsDisplayed()\n composeTestRule.onNodeWithTag(\"BottomBar\").assetDoesNotExist()\n }\n \n ```\n\nSpecify what devices your tests need\n\nIf you're running a test that performs folding actions on a device that isn't\nfoldable, the test will likely fail. To execute only the tests that are relevant\nto the running device, use the `@RequiresDeviceMode` annotation. The test runner\nautomatically skips running tests on devices that don't support the\nconfiguration being tested. You can add the device requirement rule to each test\nor an entire test class.\n\nFor example, to specify that a test should only be run on devices that support\nunfolding to a flat configuration, add the following `@RequiresDeviceMode` code\nto your test: \n\n @Test\n @RequiresDeviceMode(mode = FLAT)\n fun myUnfoldedTest() {\n ...\n }"]]