Cómo probar animaciones
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Compose ofrece ComposeTestRule
, que te permite escribir pruebas para animaciones de manera determinista con control total sobre el reloj de prueba. Esto te permite verificar los valores de animación intermedios. Además, una prueba puede ejecutarse más rápido que la duración real de la animación.
ComposeTestRule
expone su reloj de prueba como mainClock
. Puedes configurar la propiedad autoAdvance
como "false" para controlar el reloj en tu código de prueba. Después de iniciar la animación que deseas probar, el reloj puede moverse con advanceTimeBy
.
Debes tener en cuenta que advanceTimeBy
no mueve el reloj exactamente según la duración especificada. En cambio, se redondea a la duración más cercana que sea multiplicador de la duración del fotograma.
@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()
}
Recomendaciones para ti
El contenido y las muestras de código que aparecen en esta página están sujetas a las licencias que se describen en la Licencia de Contenido. Java y OpenJDK son marcas registradas de Oracle o sus afiliados.
Última actualización: 2025-08-23 (UTC)
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Falta la información que necesito","missingTheInformationINeed","thumb-down"],["Muy complicado o demasiados pasos","tooComplicatedTooManySteps","thumb-down"],["Desactualizado","outOfDate","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Problema con las muestras o los códigos","samplesCodeIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 2025-08-23 (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)"]]