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() }
为你推荐
- 注意:当 JavaScript 关闭时,会显示链接文本
- 测试你的 Compose 布局
- 其他注意事项
- 自定义动画 {:#customize-animations}