Testar animações
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
A ComposeTestRule
oferecida pelo Compose permite programar testes de animações
de forma determinística, com controle total sobre o relógio de teste. Isso permite
verificar valores de animação intermediários. Além disso, a duração do teste pode ser menor
do que a da animação.
A ComposeTestRule
exibe o relógio de teste como mainClock
. Você pode definir
a propriedade autoAdvance
como "false" no código de teste para controlar o relógio. Depois
de iniciar a animação a ser testada, o relógio pode ser adiantado com
advanceTimeBy
.
Observe que o advanceTimeBy
não adianta o relógio exatamente de acordo com a
duração especificada. Em vez disso, a duração é arredondada para o valor mais próximo
que corresponda a um multiplicador da duração do frame.
@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()
}
Recomendados para você
O conteúdo e os exemplos de código nesta página estão sujeitos às licenças descritas na Licença de conteúdo. Java e OpenJDK são marcas registradas da Oracle e/ou suas afiliadas.
Última atualização 2025-08-27 UTC.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Não contém as informações de que eu preciso","missingTheInformationINeed","thumb-down"],["Muito complicado / etapas demais","tooComplicatedTooManySteps","thumb-down"],["Desatualizado","outOfDate","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Problema com as amostras / o código","samplesCodeIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-27 UTC."],[],[],null,["Compose offers `ComposeTestRule` that allows you to write tests for animations\nin a deterministic manner with full control over the test clock. This allows you\nto verify intermediate animation values. In addition, a test can run quicker\nthan the actual duration of the animation.\n\n`ComposeTestRule` exposes its test clock as `mainClock`. You can set the\n`autoAdvance` property to false to control the clock in your test code. After\ninitiating the animation you want to test, the clock can be moved forward with\n`advanceTimeBy`.\n\nOne thing to note here is that `advanceTimeBy` doesn't move the clock exactly by\nthe specified duration. Rather, it rounds it up to the nearest duration that is\na multiplier of the frame duration.\n\n\n```kotlin\n@get:Rule\nval rule = createComposeRule()\n\n@Test\nfun testAnimationWithClock() {\n // Pause animations\n rule.mainClock.autoAdvance = false\n var enabled by mutableStateOf(false)\n rule.setContent {\n val color by animateColorAsState(\n targetValue = if (enabled) Color.Red else Color.Green,\n animationSpec = tween(durationMillis = 250)\n )\n Box(Modifier.size(64.dp).background(color))\n }\n\n // Initiate the animation.\n enabled = true\n\n // Let the animation proceed.\n rule.mainClock.advanceTimeBy(50L)\n\n // Compare the result with the image showing the expected result.\n // `assertAgainGolden` needs to be implemented in your code.\n rule.onRoot().captureToImage().assertAgainstGolden()\n}https://github.com/android/snippets/blob/5673ffc60b614daf028ee936227128eb8c4f9781/compose/snippets/src/androidTest/java/com/example/compose/snippets/animation/AnimationTestingSnippets.kt#L57-L82\n```\n\n\u003cbr /\u003e\n\nRecommended for you\n\n- Note: link text is displayed when JavaScript is off\n- [Testing your Compose layout](/develop/ui/compose/testing)\n- [Other considerations](/develop/ui/compose/migrate/other-considerations)\n- [Customize animations {:#customize-animations}](/develop/ui/compose/animation/customize)"]]