Robolectric Run Handler帖子

时间:2013-09-23 09:41:39

标签: android handler robolectric

我无法使用Robolectric测试Handler代码。例如:

public class Client {
  private Handler mMainThreadHandler;

  public interface Callback{
    void ok();
  }

  public Client() {
    mMainThreadHandler = new Handler(Looper.getMainLooper());
  }

  public void doSomeStuff(Callback callback){
    //doing...
    mMainThreadHandler.post(new Runnable(){
      @Override public void run() {
        callback.ok();
      }
    });
  }
}

如何立即在Runnable中运行代码?它在我的测试完成之前没有运行。

3 个答案:

答案 0 :(得分:11)

对于Robolectric 3.0版,您应该使用: org.robolectric.Robolectric.flushForegroundThreadScheduler

org.robolectric.shadows.ShadowLooper.runUiThreadTasks
org.robolectric.shadows.ShadowLooper.runUiThreadTasksIncludingDelayedTasks

参考:2.4 to 3.0 Upgrade Guide

答案 1 :(得分:8)

我认为这应该成功:

Robolectric.runUiThreadTasks();

或者是否安排了多项任务:

Robolectric.runUiThreadTasksIncludingDelayedTasks();

答案 2 :(得分:4)

在Robolectrie 3.0中你可以做到

HandlerThread thread = new HandlerThread("test");
thread.start();
Handler handler = new Handler(thread.getLooper());
handler.post(new Runnable() {run(){
  int a = 0;
}};
((ShadowLooper) ShadowExtractor.extract(thread.getLooper())).idle(); // this will execute line int a = 0;