Kotlin Multiplatform Development Help

使用JUnit测试Compose Multiplatform UI

Compose Multiplatform为桌面端提供了基于JUnit和Jetpack Compose测试API的测试方案。
具体实现细节请参阅Jetpack Compose文档中的测试Compose布局指南。

要实践基于JUnit的测试,我们以Kotlin跨平台向导生成的项目为例。
若需在现有项目中添加测试,可能需要将路径和命令中的composeApp替换为实际测试模块名(例如shared)。

创建测试源集并添加必要依赖:

  1. 创建测试目录: composeApp/src/desktopTest/kotlin

  2. composeApp/build.gradle.kts文件中添加依赖:

    kotlin { //... sourceSets { //... val desktopTest by getting { dependencies { implementation(compose.desktop.uiTestJUnit4) implementation(compose.desktop.currentOs) } } } }
  3. 创建名为ExampleTest.kt的测试文件并复制以下代码:

    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.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进行断言和操作 rule.onNodeWithTag("text").assertTextEquals("Hello") rule.onNodeWithTag("button").performClick() rule.onNodeWithTag("text").assertTextEquals("Compose") } }
  4. 运行测试时,点击myTest()函数旁的运行图标,或在终端执行:

    ./gradlew desktopTest

后续步骤

22 四月 2025