OwlTableau
OwlTableau

Reputation: 113

Robolectric Run Handler post

I am having trouble testing Handler code with Robolectric. For example:

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();
      }
    });
  }
}

How do I run the code in the Runnable immediately? It doesn't run before my test is done executing.

Upvotes: 11

Views: 8377

Answers (3)

Helin Wang
Helin Wang

Reputation: 4202

In Robolectrie 3.0 you can do

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;

Upvotes: 4

krossovochkin
krossovochkin

Reputation: 12122

For Robolectric version 3.0 you should use: org.robolectric.Robolectric.flushForegroundThreadScheduler
or
org.robolectric.shadows.ShadowLooper.runUiThreadTasks
org.robolectric.shadows.ShadowLooper.runUiThreadTasksIncludingDelayedTasks

Reference: 2.4 to 3.0 Upgrade Guide

Upvotes: 11

Eugen Martynov
Eugen Martynov

Reputation: 20130

I think this should make a job:

Robolectric.runUiThreadTasks();

or if there several tasks scheduled:

Robolectric.runUiThreadTasksIncludingDelayedTasks();

Upvotes: 8

Related Questions