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



我正在尝试测试一个处理某些动画的类是否会在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) }
}
}

附言: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)
}

最新更新