Тестовые анимации
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
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()
}
{% дословно %}
{% endverbatim %} Рекомендовано для вас
{% дословно %} {% endverbatim %}
Контент и образцы кода на этой странице предоставлены по лицензиям. Java и OpenJDK – это зарегистрированные товарные знаки корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-08-27 UTC.
[[["Прост для понимания","easyToUnderstand","thumb-up"],["Помог мне решить мою проблему","solvedMyProblem","thumb-up"],["Другое","otherUp","thumb-up"]],[["Отсутствует нужная мне информация","missingTheInformationINeed","thumb-down"],["Слишком сложен/слишком много шагов","tooComplicatedTooManySteps","thumb-down"],["Устарел","outOfDate","thumb-down"],["Проблема с переводом текста","translationIssue","thumb-down"],["Проблемы образцов/кода","samplesCodeIssue","thumb-down"],["Другое","otherDown","thumb-down"]],["Последнее обновление: 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)"]]