如何在Robolectric中访问后台线程?

3
我正在使用Robolectric runner测试一段代码。被测试的代码验证它没有在主线程上执行:
    if (Looper.getMainLooper().getThread() == java.lang.Thread.currentThread()) {
        new IllegalStateException("Method called on the UI thread");
    }

Robolectric测试会引发异常,但我不想这样。 我尝试从Robolectric.getBackgroundScheduler()运行代码,但仍然出现异常。

我的测试如何在不同的线程中开始运行?


1
创建一个实用方法或类并进行模拟。这是不幸的,也不是好的解决方案。 - Eugen Martynov
你使用哪个 Robolectric? - Eugen Martynov
1个回答

0

如评论中所建议,可以使用一个实用方法来进行检查:

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);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接