可用來測試不同螢幕大小的程式庫和工具

Android 提供各種工具和 API,可協助您建立測試 不同的螢幕大小和視窗大小

DeviceConfigurationOverride

DeviceConfigurationOverride 可組合函式可讓您覆寫 設定屬性,在 Compose 中測試多種螢幕大小和視窗大小 版面配置ForcedSize 覆寫值符合可用空間中的任何版面配置。 讓您在其中執行 所有螢幕大小的 UI 測試。舉例來說,您可以使用小型手機板型規格 執行所有 UI 測試,包括針對大型手機、摺疊式裝置以及 平板電腦。

   DeviceConfigurationOverride(
        DeviceConfigurationOverride.ForcedSize(DpSize(1280.dp, 800.dp))
    ) {
        MyScreen() // Will be rendered in the space for 1280dp by 800dp without clipping.
    }
敬上
圖 1.使用 DeviceConfigurationOverride,將平板電腦版面配置置於較小的板型規格裝置上,例如「*Now in Android*」。

此外,您也可以使用這個可組合函式設定字型大小、主題和其他 建議您針對不同視窗大小測試這些屬性。

Robolectric

使用 Robolectric 在 JVM 上執行 Compose 或以 View 為基礎的 UI 測試 locally:無需任何裝置或模擬器。您可以設定 靈活運用特定螢幕大小和其他實用屬性。

在下方範例中的 Now in Android 中,Robolectric 已完成設定 以 480 dpi 的解析度模擬 1000 x 1000 dp 的螢幕大小:

@RunWith(RobolectricTestRunner::class)
// Configure Robolectric to use a very large screen size that can fit all of the test sizes.
// This allows enough room to render the content under test without clipping or scaling.
@Config(qualifiers = "w1000dp-h1000dp-480dpi")
class NiaAppScreenSizesScreenshotTests { ... }

您也可以在測試主體中設定限定詞,如以下程式碼片段所示: Now in Android 範例:

val (width, height, dpi) = ...

// Set qualifiers from specs.
RuntimeEnvironment.setQualifiers("w${width}dp-h${height}dp-${dpi}dpi")

請注意,RuntimeEnvironment.setQualifiers() 會更新系統並 重新設定應用程式資源,但不會觸發任何動作 追蹤活動

詳情請參閱 Robolectric 裝置設定說明文件。

Gradle 管理的裝置

Gradle 管理的裝置 (GMD) Android Gradle 外掛程式 可讓您定義模擬器和實體裝置的規格 檢測設備測試的執行狀況。為具有下列特性的裝置建立規格: 不同的螢幕大小來實作測試策略,但前提是必須進行測試 只能在特定螢幕大小上執行將 GMD 與持續整合搭配使用 可以確保在必要時執行合適的測試 佈建和啟動模擬器並簡化 CI 設定。

android {
    testOptions {
        managedDevices {
            devices {
                // Run with ./gradlew nexusOneApi30DebugAndroidTest.
                nexusOneApi30(com.android.build.api.dsl.ManagedVirtualDevice) {
                    device = "Nexus One"
                    apiLevel = 30
                    // Use the AOSP ATD image for better emulator performance
                    systemImageSource = "aosp-atd"
                }
                // Run with ./gradlew  foldApi34DebugAndroidTest.
                foldApi34(com.android.build.api.dsl.ManagedVirtualDevice) {
                    device = "Pixel Fold"
                    apiLevel = 34
                    systemImageSource = "aosp-atd"
                }
            }
        }
    }
}

您可以在 testing-samples 專案中找到多個 GMD 範例。

Firebase Test Lab

請使用 Firebase Test Lab (FTL) 或類似的裝置農場服務 模擬您可能無法存取的特定實際裝置,例如 各種大小的摺疊式裝置或平板電腦。Firebase Test Lab 需要付費 並免付費使用多項服務。FTL 也支援在模擬器上執行測試。 這些服務可以提高檢測設備測試的可靠性和速度,因為 預先佈建裝置和模擬器

如要瞭解如何搭配使用 FTL 與 GMD,請參閱調度測試資源: Gradle 管理的裝置。

使用測試執行工具測試篩選功能

最佳測試策略不應重複驗證同一件事,因此大部分的 使用者介面測試不需要在多部裝置上執行。通常您會篩選 UI 並透過手機板型規格執行所有或大部分測試,且只執行一部分測試。 螢幕尺寸各不相同。

您可以為特定裝置加上註解,然後將測試通過 AndroidJUnitRunner 的引數 測試。

舉例來說,您可以建立不同的註解:

annotation class TestExpandedWidth
annotation class TestCompactWidth

並用於不同的測試:

class MyTestClass {

    @Test
    @TestExpandedWidth
    fun myExample_worksOnTablet() {
        ...
    }

    @Test
    @TestCompactWidth
    fun myExample_worksOnPortraitPhone() {
        ...
    }

}

接著,您可以使用 android.testInstrumentationRunnerArguments.annotation 屬性來篩選特定測試。舉例來說 使用 Gradle 管理的裝置:

$ ./gradlew pixelTabletApi30DebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.annotation='com.sample.TestExpandedWidth'

如果您沒有使用 GMD,而且是透過 CI 管理模擬器,請先確認 正確的模擬器或裝置已準備就緒並處於連線狀態, 執行檢測設備測試:

$ ./gradlew connectedAndroidTest -Pandroid.testInstrumentationRunnerArguments.annotation='com.sample.TestExpandedWidth'

請注意,Espresso Device (請參閱下一節) 也可以使用 裝置屬性。

Espresso 裝置

使用 Espresso 裝置,在採用任意映像檔的測試中對模擬器執行動作 檢測設備測試的類型,包括 Espresso、Compose 或 UI Automator 測試。 這些動作可能包括設定螢幕大小或切換摺疊式裝置狀態 例如安全性、狀態和型態舉例來說,您可以控制摺疊式裝置模擬器,並設為 桌面模式。Espresso 裝置也包含 JUnit 規則和註解 需要特定功能:

@RunWith(AndroidJUnit4::class)
class OnDeviceTest {

    @get:Rule(order=1) val activityScenarioRule = activityScenarioRule<MainActivity>()

    @get:Rule(order=2) val screenOrientationRule: ScreenOrientationRule =
        ScreenOrientationRule(ScreenOrientation.PORTRAIT)

    @Test
    fun tabletopMode_playerIsDisplayed() {
        // Set the device to tabletop mode.
        onDevice().setTabletopMode()
        onView(withId(R.id.player)).check(matches(isDisplayed()))
    }
}

請注意,Espresso Device 仍處於 Alpha 版階段,具有以下功能: 規定:

  • Android Gradle 外掛程式 8.3 以上版本
  • Android Emulator 33.1.10 以上版本
  • 搭載 API 級別 24 以上版本的 Android 虛擬裝置

篩選測試

Espresso 裝置可讀取已連結裝置的屬性,方便你執行以下動作: 篩選測試。如果不符合加註的規定 系統就會略過測試

RequiresDeviceMode 註解

RequiresDeviceMode 註解可以多次用於表示 只有在支援「所有」DeviceMode 值時,才會執行測試 應用程式。

class OnDeviceTest {
    ...
    @Test
    @RequiresDeviceMode(TABLETOP)
    @RequiresDeviceMode(BOOK)
    fun tabletopMode_playerIdDisplayed() {
        // Set the device to tabletop mode.
        onDevice().setTabletopMode()
        onView(withId(R.id.player)).check(matches(isDisplayed()))
    }
}

需要顯示註解

RequiresDisplay 註解可讓您指定 透過定義尺寸值區的大小類別調整裝置畫面 參考官方的視窗大小類別

class OnDeviceTest {
    ...
    @Test
    @RequiresDisplay(EXPANDED, COMPACT)
    fun myScreen_expandedWidthCompactHeight() {
        ...
    }
}

調整顯示畫面大小

使用 setDisplaySize() 方法調整螢幕大小 執行程式碼請將此方法與 DisplaySizeRule 搭配使用 類別,確保在測試期間所做的任何變更都能在 下一個測試。

@RunWith(AndroidJUnit4::class)
class ResizeDisplayTest {

    @get:Rule(order = 1) val activityScenarioRule = activityScenarioRule<MainActivity>()

    // Test rule for restoring device to its starting display size when a test case finishes.
    @get:Rule(order = 2) val displaySizeRule: DisplaySizeRule = DisplaySizeRule()

    @Test
    fun resizeWindow_compact() {
        onDevice().setDisplaySize(
            widthSizeClass = WidthSizeClass.COMPACT,
            heightSizeClass = HeightSizeClass.COMPACT
        )
        // Verify visual attributes or state restoration.
    }
}

使用 setDisplaySize() 調整螢幕大小時,不會影響密度。 因此,如果尺寸與目標裝置不符,系統會測試 失敗,並顯示 UnsupportedDeviceOperationException。如要避免測試 在本例中,請使用 RequiresDisplay 註解篩除這些元素:

@RunWith(AndroidJUnit4::class)
class ResizeDisplayTest {

    @get:Rule(order = 1) var activityScenarioRule = activityScenarioRule<MainActivity>()

    // Test rule for restoring device to its starting display size when a test case finishes.
    @get:Rule(order = 2) var displaySizeRule: DisplaySizeRule = DisplaySizeRule()

    /**
     * Setting the display size to EXPANDED would fail in small devices, so the [RequiresDisplay]
     * annotation prevents this test from being run on devices outside the EXPANDED buckets.
     */
    @RequiresDisplay(
        widthSizeClass = WidthSizeClassEnum.EXPANDED,
        heightSizeClass = HeightSizeClassEnum.EXPANDED
    )
    @Test
    fun resizeWindow_expanded() {
        onDevice().setDisplaySize(
            widthSizeClass = WidthSizeClass.EXPANDED,
            heightSizeClass = HeightSizeClass.EXPANDED
        )
        // Verify visual attributes or state restoration.
    }
}

StateRestorationTester

StateRestorationTester 類別可用來測試狀態還原作業 無需重新建立活動這可加快測試速度 但更可靠,因為重建活動是一個複雜的程序,包含多個 同步處理機制:

@Test
fun compactDevice_selectedEmailEmailRetained_afterConfigChange() {
    val stateRestorationTester = StateRestorationTester(composeTestRule)

    // Set content through the StateRestorationTester object.
    stateRestorationTester.setContent {
        MyApp()
    }

    // Simulate a config change.
    stateRestorationTester.emulateSavedInstanceStateRestore()
}

視窗測試程式庫

Window Testing 程式庫內含公用程式,可協助您編寫需要使用 啟用或確認與視窗管理相關的功能,例如活動 嵌入或折疊式功能。構件可透過 Google 的 Maven 存放區

舉例來說,您可以使用 FoldingFeature() 函式來產生 自訂 FoldingFeature,您可以在 Compose 預覽中使用。在 Java 中 使用 createFoldingFeature() 函式。

在 Compose 預覽中,您可以透過以下方式實作 FoldingFeature

@Preview(showBackground = true, widthDp = 480, heightDp = 480)
@Composable private fun FoldablePreview() =
    MyApplicationTheme {
        ExampleScreen(
            displayFeatures = listOf(FoldingFeature(Rect(0, 240, 480, 240)))
        )
 }

此外,您也可以使用 TestWindowLayoutInfo() 函式。 以下範例使用 FoldingFeature 來模擬 HALF_OPENED 等待螢幕中央的垂直轉軸,再檢查 版面配置符合預期:

Compose

import androidx.window.layout.FoldingFeature.Orientation.Companion.VERTICAL
import androidx.window.layout.FoldingFeature.State.Companion.HALF_OPENED
import androidx.window.testing.layout.FoldingFeature
import androidx.window.testing.layout.TestWindowLayoutInfo
import androidx.window.testing.layout.WindowLayoutInfoPublisherRule

@RunWith(AndroidJUnit4::class)
class MediaControlsFoldingFeatureTest {

    @get:Rule(order=1)
    val composeTestRule = createAndroidComposeRule<ComponentActivity>()

    @get:Rule(order=2)
    val windowLayoutInfoPublisherRule = WindowLayoutInfoPublisherRule()

    @Test
    fun foldedWithHinge_foldableUiDisplayed() {
        composeTestRule.setContent {
            MediaPlayerScreen()
        }

        val hinge = FoldingFeature(
            activity = composeTestRule.activity,
            state = HALF_OPENED,
            orientation = VERTICAL,
            size = 2
        )

        val expected = TestWindowLayoutInfo(listOf(hinge))
        windowLayoutInfoPublisherRule.overrideWindowLayoutInfo(expected)

        composeTestRule.waitForIdle()

        // Verify that the folding feature is detected and media controls shown.
        composeTestRule.onNodeWithTag("MEDIA_CONTROLS").assertExists()
    }
}

View

import androidx.window.layout.FoldingFeature.Orientation
import androidx.window.layout.FoldingFeature.State
import androidx.window.testing.layout.FoldingFeature
import androidx.window.testing.layout.TestWindowLayoutInfo
import androidx.window.testing.layout.WindowLayoutInfoPublisherRule

@RunWith(AndroidJUnit4::class)
class MediaControlsFoldingFeatureTest {

    @get:Rule(order=1)
    val activityRule = ActivityScenarioRule(MediaPlayerActivity::class.java)

    @get:Rule(order=2)
    val windowLayoutInfoPublisherRule = WindowLayoutInfoPublisherRule()

    @Test
    fun foldedWithHinge_foldableUiDisplayed() {
        activityRule.scenario.onActivity { activity ->
            val feature = FoldingFeature(
                activity = activity,
                state = State.HALF_OPENED,
                orientation = Orientation.VERTICAL)
            val expected = TestWindowLayoutInfo(listOf(feature))
            windowLayoutInfoPublisherRule.overrideWindowLayoutInfo(expected)
        }

        // Verify that the folding feature is detected and media controls shown.
        onView(withId(R.id.media_controls)).check(matches(isDisplayed()))
    }
}

您可以在 WindowManager 專案中找到更多範例。

其他資源

說明文件

範例

程式碼研究室