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

Tre*_*kaz 3 testing kotlin compose-desktop

给出一些简单的内容:

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

如果我尝试测试该内容是否已显示:

@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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我明白了:

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)
    ...
Run Code Online (Sandbox Code Playgroud)

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

还有另一种方法可以做到我所缺少的吗?所有的教程都谈到了assertIsDisplayed()这种方式,但也许还有其他选择?

Pst*_*str 7

它不是直接替代品,但不幸的是,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()
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么忘记这个?无论如何,测试都很重要。如果您可以断言您的元素存在并已实例化,为什么不呢? (2认同)