Skip to content

使用 JUnit 測試 Compose Multiplatform UI

Compose Multiplatform 桌面版提供了一個基於 JUnit 與 Jetpack Compose 測試 API 的測試 API。 有關實作的更多詳細資訊,請參閱 Jetpack Compose 文件中的 測試您的 Compose 版面配置 指南。

關於在所有支援平台上的 UI 測試功能,請參閱 測試 Compose Multiplatform UI 文章。

為了觀察基於 JUnit 的測試實際運作,讓我們從 Kotlin Multiplatform 精靈 產生的專案開始。 如果您是在現有專案中加入測試,您可能需要將路徑和指令中的 shared 替換為您正在測試的模組名稱。

建立測試原始碼集並加入必要的相依性:

  1. 建立一個測試目錄:shared/src/desktopTest/kotlin

  2. shared/build.gradle.kts 檔案中,加入以下相依性:

    kotlin
    kotlin { 
        //...
        sourceSets { 
            //...
            val desktopTest by getting { 
                dependencies {
                    implementation(compose.desktop.uiTestJUnit4)
                    implementation(compose.desktop.currentOs)
                }
            }
        }
    }
  3. 建立一個名為 ExampleTest.kt 的測試檔案,並將以下程式碼複製到其中:

    kotlin
    import androidx.compose.material.*
    import androidx.compose.runtime.*
    import androidx.compose.ui.Modifier
    import androidx.compose.ui.test.*
    import androidx.compose.ui.platform.testTag
    import androidx.compose.ui.test.junit4.v2.createComposeRule
    import org.junit.Rule
    import org.junit.Test
    
    class ExampleTest {
        @get:Rule
        val rule = createComposeRule()
    
        @Test
        fun myTest(){
            // 宣告一個模擬 UI 以展示 API 呼叫
            //
            // 替換為您自己的宣告以測試專案中的程式碼
            rule.setContent {
                var text by remember { mutableStateOf("Hello") }
    
                Text(
                    text = text,
                    modifier = Modifier.testTag("text")
                )
                Button(
                    onClick = { text = "Compose" },
                    modifier = Modifier.testTag("button")
                ) {
                    Text("Click me")
                }
            }
    
            // 使用基於 JUnit 測試 API 的斷言和操作來測試宣告的 UI
            rule.onNodeWithTag("text").assertTextEquals("Hello")
            rule.onNodeWithTag("button").performClick()
            rule.onNodeWithTag("text").assertTextEquals("Compose")
        }
    }
  4. 若要執行測試,請點擊 myTest() 函式旁邊邊欄中的執行圖示,或在終端中執行以下指令:

    shell
    ./gradlew desktopTest

接續步驟