Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 300
OwlTableau Avatar asked Sep 23 '13 09:09

OwlTableau


2 Answers

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

like image 131
krossovochkin Avatar answered Nov 15 '22 18:11

krossovochkin


I think this should make a job:

Robolectric.runUiThreadTasks();

or if there several tasks scheduled:

Robolectric.runUiThreadTasksIncludingDelayedTasks();
like image 33
Eugen Martynov Avatar answered Nov 15 '22 20:11

Eugen Martynov