Compose 提供 ComposeTestRule
,可让您以确定性的方式编写动画测试,并完全控制测试时钟。这样,您就可以验证中间动画值。此外,测试的运行速度可能比动画的实际时长快。
ComposeTestRule
将其测试时钟公开为 mainClock
。您可以将 autoAdvance
属性设置为 false,以控制测试代码中的时钟。启动要测试的动画后,可以使用 advanceTimeBy
将时钟提前。
有一点需要注意,advanceTimeBy
不会按指定时长精确地移动时钟,而是向上舍入为最接近的时长(帧时长的倍数)。
@get:Rule val rule = createComposeRule() @Test fun testAnimationWithClock() { // Pause animations rule.mainClock.autoAdvance = false var enabled by mutableStateOf(false) rule.setContent { val color by animateColorAsState( targetValue = if (enabled) Color.Red else Color.Green, animationSpec = tween(durationMillis = 250) ) Box(Modifier.size(64.dp).background(color)) } // Initiate the animation. enabled = true // Let the animation proceed. rule.mainClock.advanceTimeBy(50L) // Compare the result with the image showing the expected result. // `assertAgainGolden` needs to be implemented in your code. rule.onRoot().captureToImage().assertAgainstGolden() }
目前没有任何推荐文档页面。
请尝试登录您的 Google 账号。