kotlin - Compose 桌面测试 - 如何检查某些内容是否可见?

标签 kotlin testing compose-desktop

给定一些简单的内容:

@Composable
fun MyContent() {
    var showThing by remember { mutableStateOf(false) }
    if (showThing) {
        Box(Modifier.testTag("thing")) {
            Text("The Thing")
        }
    }
}

如果我尝试测试该事物是否已显示:

@OptIn(ExperimentalTestApi::class)
class Scratch {
    @get:Rule
    val compose = createComposeRule()

    @Test
    fun test() {
        runBlocking(Dispatchers.Main) {
            compose.setContent {
                MyContent()
            }
            compose.awaitIdle()

            compose.onNodeWithTag("thing").assertIsNotDisplayed()
        }
    }
}

我明白了:

An operation is not implemented.
kotlin.NotImplementedError: An operation is not implemented.
    at androidx.compose.ui.test.DesktopAssertions_desktopKt.checkIsDisplayed(DesktopAssertions.desktop.kt:23)
    at androidx.compose.ui.test.AssertionsKt.assertIsNotDisplayed(Assertions.kt:49)
    at Scratch$test$1.invokeSuspend(Scratch.kt:44)
    at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
    at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
    ...

我认为测试是否显示某些东西是最基本的测试,但框架还不支持。测试框架是实验性的,所以我期待找到缺失的东西,但不是这样。

是否有另一种方法可以做到这一点,我错过了?那里的所有教程都在谈论 assertIsDisplayed() 是方法,但也许还有其他选择?

最佳答案

它不是直接替代品,但不幸的是,JB Compose Desktop 在 UI 测试套件中存在这些限制。除了仅使用 JUnit 4,并且与较新版本不兼容之外,许多断言方法和屏幕交互方法都没有实现,例如您尝试使用的 .assertIsNotDisplayed(),以及类似 .performTextInput() 的操作。

您的问题的替代方法是使用其他方法,例如 .assertDoesNotExist().assertExists()

它不会告诉您该元素是否在屏幕边界内并且可见,但至少会告诉您您的节点存在并且已实例化,这是有总比没有好。

在 JetBrains 实现完整的桌面测试套件之前,我们需要使用现有的东西,或者尝试实现一些东西作为解决方法。

在您的情况下,这将起作用:

@OptIn(ExperimentalTestApi::class)
class Scratch {
    @get:Rule
    val compose = createComposeRule()

@Test
fun test() {
    runBlocking(Dispatchers.Main) {
        compose.setContent {
            MyContent()
        }
        compose.awaitIdle()

        compose.onNodeWithTag("thing").assertDoesNotExist()
    }
}

关于kotlin - Compose 桌面测试 - 如何检查某些内容是否可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71701872/

相关文章:

android - Kotlin Mockk 错误 : Missing calls inside verify { . .. } block

kotlin - 使用外部 kotlinx Serializer 序列化列表

ruby-on-rails - 在 Rspec 中测试创建变量赋值

kotlin - 如何在 Kotlin Compose 桌面中加载图像?

kotlin - 如何垂直对齐文本字段中的文本和前导/尾随图标

android - java.lang.IllegalStateException : Fragment already added: MovieFragment 错误

spring-boot - 将主题名称数组列表传递给@KafkaListener

c++ - 是否可以将 TDD 与图像处理算法一起使用?

android - Mockk 模拟 Kotlin 的私有(private)属性(property)

android-jetpack-compose - 如何在 Jetpack Compose 中创建编辑器?