【问题标题】:How to access the background thread in Robolectric?如何访问 Robolectric 中的后台线程?
【发布时间】:2019-05-05 22:45:53
【问题描述】:

我正在 Robolectric 跑步者中测试代码。被测代码验证它没有在主线程上执行:

    if (Looper.getMainLooper().getThread() == java.lang.Thread.currentThread()) {
        new IllegalStateException("Method called on the UI thread");
    }

Robolectric 测试引发了这个异常,我不希望这样。 我尝试从 Robolectric.getBackgroundScheduler() 运行代码,但仍然有异常。

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

【问题讨论】:

  • 创建一个实用方法或类并模拟它。这是不幸的,不是很好的解决方案
  • 你使用哪种机器人?

标签: multithreading robolectric


【解决方案1】:

根据 cmets 的建议,检查可以使用实用方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多