首页 > 解决方案 > 等待动画完成并在单元测试中检查结果

问题描述

我在 kotlin 中有一个单元测试,它执行 longClick,然后检查视图的宽度是否发生了变化。宽度应该在半秒内改变。但无论我等多久,收到的宽度都不像预期的那样。

@Test
fun testLongClick() {
    var initialWidth = 0
    val listener = mock<TestInterface>(TestInterface::class.java)
    view?.let {


        it.findViewById<ImpulsesGroup>(R.id.test_default_impulse).getChildAt(2).setOnLongClickListener { child ->
            (child as ImpulsesButton).onLongClick(child, it.findViewById<ImpulsesGroup>(R.id.test_default_impulse), listener)
        }
        initialWidth = it.findViewById<ImpulsesGroup>(R.id.test_default_impulse).width
        assertThat("initial width", initialWidth, greaterThan(0))

        runOnUiThread {
            it.findViewById<ImpulsesGroup>(R.id.test_default_impulse).getChildAt(2).performLongClick()
        }

        await().atLeast(5, TimeUnit.SECONDS)
        assertThat(view!!.findViewById<ImpulsesGroup>(R.id.test_default_impulse).width, Matchers.equalTo(3 * initialWidth))
    }
}

似乎在动画完成之前检查了最终的assetThat()!

标签: androidunit-testingkotlin

解决方案


private static class AsynchroniClass extends AsyncTask<Void, Void, Void> {


        protected Void doInBackground(Void... voids) {
          //what functions you need to do in the background
         //in your case get Current width of a view 
        }

        @Override
        protected void onPostExecute(Void result) {
            //now after you have the width call your function
        }
    }

然后不要忘记AsynchroniClassonCreateView这样调用:

new AsynchroniClass().execute();

推荐阅读