Robolectric运行处理程序的职位

我无法用RobolectrictestingHandler代码。 例如:

 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运行代码? 在我的testing完成之前它不运行。

Solutions Collecting From Web of "Robolectric运行处理程序的职位"

我认为这应该是一个工作:

 Robolectric.runUiThreadTasks(); 

或者如果有几个任务计划:

 Robolectric.runUiThreadTasksIncludingDelayedTasks(); 

对于Robolectric版本3.0,您应该使用: org.robolectric.Robolectric.flushForegroundThreadScheduler
要么
org.robolectric.shadows.ShadowLooper.runUiThreadTasks
org.robolectric.shadows.ShadowLooper.runUiThreadTasksIncludingDelayedTasks

参考: 2.4到3.0升级指南

在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;