Reputation: 113
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
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
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
Reputation: 20130
I think this should make a job:
Robolectric.runUiThreadTasks();
or if there several tasks scheduled:
Robolectric.runUiThreadTasksIncludingDelayedTasks();
Upvotes: 8