0

使用 robolectric 版本 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()).idleFor(1, TimeUnit.MILLISECONDS); 这很好用吗?

作为文档 idleFor 将系统时钟提前给定时间,然后执行在给定时间之前或在给定时间安排的所有已发布任务。这是什么意思推进系统时钟我的测试是如何通过使用 idleFor() 而不是 idle()

4

1 回答 1

0

我们可以在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);

我们可以检查ShadowPausedMessageQueuegetNextScheduledTaskTime()

  Duration getNextScheduledTaskTime() {
    Message next = peekNextExecutableMessage();

    if (next == null) {
      return Duration.ZERO;
    }
    return Duration.ofMillis(convertWhenToScheduledTime(shadowOfMsg(next).getWhen()));
  }
于 2021-09-09T12:05:12.087 回答