[英]Robolectric Run Handler post
I am having trouble testing Handler
code with Robolectric. 我在使用Robolectric测试
Handler
代码时遇到问题。 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? 如何立即在
Runnable
运行代码? It doesn't run before my test is done executing. 它在我的测试完成执行之前没有运行。
For Robolectric version 3.0 you should use: org.robolectric.Robolectric.flushForegroundThreadScheduler
对于Robolectric 3.0版,您应该使用:
org.robolectric.Robolectric.flushForegroundThreadScheduler
or 要么
org.robolectric.shadows.ShadowLooper.runUiThreadTasks
org.robolectric.shadows.ShadowLooper.runUiThreadTasksIncludingDelayedTasks
Reference: 2.4 to 3.0 Upgrade Guide 参考: 2.4到3.0升级指南
I think this should make a job: 我认为这应该是一份工作:
Robolectric.runUiThreadTasks();
or if there several tasks scheduled: 或者如果安排了几项任务:
Robolectric.runUiThreadTasksIncludingDelayedTasks();
In Robolectrie 3.0 you can do 在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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.