我正在 Robolectric 运行器中测试代码。被测代码验证它没有在主线程上执行:
if (Looper.getMainLooper().getThread() == java.lang.Thread.currentThread()) {
new IllegalStateException("Method called on the UI thread");
}
Robolectric 测试引发了这个异常,我不想这样。
我尝试从 Robolectric.getBackgroundScheduler()
运行代码,但我仍然遇到异常。
我的测试如何在不同的线程中开始运行?
最佳答案
正如评论中所建议的,检查可以使用实用方法:
static void checkMainThread() {
if (isRunningInRobolectric()) {
return;
}
if (Looper.getMainLooper().getThread() == java.lang.Thread.currentThread()) {
new IllegalStateException("Method called on the UI thread");
}
}
static boolean isRunningInRobolectric() {
return "robolectric".equals(Build.FINGERPRINT);
}
关于multithreading - 如何访问 Robolectric 中的后台线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31326098/