ทดสอบภาพเคลื่อนไหว

เขียนข้อเสนอ 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()
}