multithreading - 如何访问 Robolectric 中的后台线程?

标签 multithreading robolectric

我正在 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/

相关文章:

java - 带有外部库的 Robolectric NoClassDefFoundError

c++ - 如何修复 OpenMP 程序的 gdb 运行中的线程数

c++ - Linux C++ : Does a return from main() cause a multithreaded app to terminate?

java - 执行者完成服务?如果我们有invokeAll,为什么还需要一个?

Robolectric 2.2 中的 android.content.res.Resources$NotFoundException

android - 如何在 Android Studio 中设置 robolectric

java - Android Studio 1.1.0 + Robolectric 2.4 导致 java.lang.annotation.AnnotationFormatError

android - 蓝牙连接的线程在连接后立即关闭 socket

java - 对 ThreadPoolExecutor 内的各个线程设置超时