Android测试用例robolelectric Shadowlooper idle VS idleFor



使用robolelectric version 4.5.1

shadowOf(getMainLooper()).idleFor(1, TimeUnit.MILLISECONDS);

shadowOf(getMainLooper()).idle();

shadowOf (getMainLooper ()) .idle ();导致我的测试用例失败给出以下异常消息

Main looper has queued unexecuted runnables. This might be the cause of the test 
failure. You might need a shadowOf(getMainLooper()).idle() call.
java.lang.Exception: Main looper has queued unexecuted runnables. This might be the cause of the test failure. You might need a shadowOf(getMainLooper()).idle() call.
at org.robolectric.android.internal.AndroidTestEnvironment.checkStateAfterTestFailure(AndroidTestEnvironment.java:502)
at org.robolectric.RobolectricTestRunner$HelperTestRunner$1.evaluate(RobolectricTestRunner.java:581)
at org.robolectric.internal.SandboxTestRunner$2.lambda$evaluate$0(SandboxTestRunner.java:278)
at org.robolectric.internal.bytecode.Sandbox.lambda$runOnMainThread$0(Sandbox.java:89)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)

但shadowOf (getMainLooper())。TimeUnit.MILLISECONDS idleFor(1日);这是如何工作的?

as documentation idleFor将系统时钟提前到给定时间,然后执行在给定时间之前或在给定时间安排的所有已发布任务。提高系统时钟我的测试是如何通过使用idleFor()而不是idle()

我们可以在ShadowPausedLooper中找到这两个函数:

@Override
public void idle() {
executeOnLooper(new IdlingRunnable());
}
@Override
public void idleFor(long time, TimeUnit timeUnit) {
long endingTimeMs = SystemClock.uptimeMillis() + timeUnit.toMillis(time);
long nextScheduledTimeMs = getNextScheduledTaskTime().toMillis();
while (nextScheduledTimeMs != 0 && nextScheduledTimeMs <= endingTimeMs) {
SystemClock.setCurrentTimeMillis(nextScheduledTimeMs);
idle();
nextScheduledTimeMs = getNextScheduledTaskTime().toMillis();
}
SystemClock.setCurrentTimeMillis(endingTimeMs);
// the last SystemClock update might have added new tasks to the main looper via Choreographer
// so idle once more.
idle();
}

idle()将只立即运行Runnables,而idleFor()将检查下一个计划任务,如果存在则移动系统时间SystemClock.setCurrentTimeMillis(nextScheduledTimeMs);

我们可以为getNextScheduledTaskTime()检查ShadowPausedMessageQueue

Duration getNextScheduledTaskTime() {
Message next = peekNextExecutableMessage();
if (next == null) {
return Duration.ZERO;
}
return Duration.ofMillis(convertWhenToScheduledTime(shadowOfMsg(next).getWhen()));
}

相关内容

  • 没有找到相关文章

最新更新