如何在 Android 测试中等待 X 毫秒?

How to wait for X milliseconds in an Android Test?

我正在尝试测试处理某些动画的 class 在 x 毫秒内更改给定对象的值。

我想做的测试很“简单”

  1. 检查totalAnimationDuration / 2后当前值是否大于初始值
  2. 检查 totalAnimationDuration 之后的值是否是我想要的值。

我的测试现在看起来像这样:

    fun start() {
        InstrumentationRegistry.getInstrumentation().runOnMainSync {
            val linearAnimation = LinearAnimation()
            linearAnimation.start("Name", 0f, 1f, ::setValueTester)
            Thread.sleep(2000)
            assertEquals(1, currentValue)
        }

    }

我遇到的问题是 Thread.sleep(2000) 睡眠测试它自己所以 start 内的完整动画发生在 sleepassert

之后

尝试使用 Handler 和 postDelayed 而不是 Thread.sleep()。

例如

Handler().postDelayed({
TODO("Do something")
}, 2000)

您可以将 Awaitility 添加到您的项目中并表达您的期望,如下所示:

fun start() {
    InstrumentationRegistry.getInstrumentation().runOnMainSync {
        val linearAnimation = LinearAnimation()
        linearAnimation.start("Name", 0f, 1f, ::setValueTester)
        await().atMost(5, SECONDS).until{ assertEquals(1, currentValue) }

    }

}

PS: Awaitility 还提供了一个Kotlin DSL.

问题是我在错误的线程上进行睡眠。这是我的工作解决方案:

    fun start() {
        // Test Thread
        val linearAnimation = LinearAnimation()

        InstrumentationRegistry.getInstrumentation().runOnMainSync {    
        // Ui Thread
            linearAnimation.start("Name", 0f, 1f, ::setValueTester)
        }
        
        // Sleep the Test thread until the UI thread is done
        Thread.sleep(2000)
        assertEquals(1, currentValue)

    }