撰寫可折迭裝置的 Jetpack Compose 測試

Jetpack Compose 提供 測試 API ,可用來測試您的版面配置,與傳統檢視系統搭配使用 一樣。 Jetpack Window Manager 也提供 測試程式庫 ,可讓您輕鬆地模擬 FoldingFeature 物件。 使用這些資源,您可以在 Compose 專案中撰寫已檢測的 UI 測試,以進行可折迭和雙螢幕裝置。

ComposeTesting 程式庫

若要減少撰寫可折迭測試所需的程式碼數量,您也可以使用 ComposeTesting 程式庫,這是測試 工具組的一部分。 此程式庫包含模擬 FoldingFeature 物件的公用程式方法,以及撰寫 UI 測試的其他實用功能,包括撥動手勢和字串資源協助程式方法。

若要在測試中使用 ComposeTesting 程式庫,請務必按一下本文中程式碼片段的 [ 使用 ComposeTesting 程式庫 ] 索引標籤。

安裝程式

  1. androidTest 目錄中建立新的測試類別檔案。 您稍後會在此新增測試規則和測試的程式碼片段。

  2. 請確定您在最上層build.gradle檔案中有存放 mavenCentral() 庫:

    allprojects {
        repositories {
            google()
            mavenCentral()
         }
    }
    
  3. 將下列相依性新增至模組層級 build.gradle 檔案 (目前版本可能與此處所示) 不同:

    androidTestImplementation "androidx.compose.ui:ui-test-junit4:1.3.0"
    androidTestImplementation "androidx.window:window-testing:1.0.0"
    
    // Only necessary if Jetpack Window Manager isn't imported for implementation
    androidTestImplementation "androidx.window:window:1.0.0"
    
  4. compileSdkVersion確定 已設定為 API 33,並將 targetSdkVersion 設定為模組層級build.gradle檔案中的 API 32 或更新版本:

    android { 
        compileSdkVersion 33
    
        defaultConfig { 
            targetSdkVersion 32
        } 
        ... 
    }
    
  5. TestRule建立可執行 Compose 檢查和模擬折迭功能的 。 您可以將兩個規則鏈結在一 WindowLayoutInfo 起:發行者規則和 Android Compose 測試規則。

    private val composeTestRule = createAndroidComposeRule<MainActivity>()
    private val publisherRule = WindowLayoutInfoPublisherRule()
    
    @get:Rule
    val testRule: TestRule
    
    init {
        testRule = RuleChain.outerRule(publisherRule).around(composeTestRule)
    }
    

如何撰寫測試

若要撰寫可折迭和雙螢幕裝置的 Compose 測試,請遵循下列四個步驟:

  1. 設定測試的內容
  2. 模擬 FoldingFeature
  3. 尋找要測試的節點 ()
  4. 在節點上執行判斷提示或動作, (s)

下列程式碼片段顯示一個範例測試,其會檢查是否在垂直 FoldingFeature 出現時,可組合顯示 TwoPaneSample 「pane 1」 和 「pane 2」 文字元素。

@Test
fun sample_verticalFoldingFeature_showsTwoPanes() {
    // 1. Optional: set the content of the test (default is MainActivity content)
    composeTestRule.activity.setContent {
        TwoPaneSample()
    }

    // 2. Simulate a vertical FoldingFeature
    composeTestRule.activityRule.scenario.onActivity { activity ->
        val verticalFoldingFeature = FoldingFeature(
            activity = activity,
            orientation = FoldingFeature.Orientation.VERTICAL
        )
        val windowLayoutInfo = TestWindowLayoutInfo(listOf(verticalFoldingFeature))
        publisherRule.overrideWindowLayoutInfo(windowLayoutInfo)
    }

    // 3. Find the nodes to test and 4. Perform assertions on the nodes
    composeTestRule.onNodeWithText("pane 1").assertIsDisplayed()
    composeTestRule.onNodeWithText("pane 2").assertIsDisplayed()
}

撰寫自己的測試時,您可以根據您的需求自訂每個步驟。 任何可撰寫的都可以進入 setContent Lambda,而且您可以變更 FoldingFeature的位置、大小、方向和狀態。

資源

若要深入瞭解使用 Jetpack Compose 和 Jetpack 視窗管理員進行測試,請參閱下列資源: