我无法使用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
中运行代码?它在我的测试完成之前没有运行。
答案 0 :(得分:11)
对于Robolectric 3.0版,您应该使用:
org.robolectric.Robolectric.flushForegroundThreadScheduler
或
org.robolectric.shadows.ShadowLooper.runUiThreadTasks
org.robolectric.shadows.ShadowLooper.runUiThreadTasksIncludingDelayedTasks
答案 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;