【问题标题】:Robolectric, create Thread without looperRobolectric,创建没有弯针的线程
【发布时间】:2016-05-01 16:15:31
【问题描述】:

我正在尝试在没有活套的情况下在 robolectric 中创建线程。
我需要使用 Handler 实例化测试我的代码,这应该会失败。

我期待“java.lang.RuntimeException:无法在未调用 Looper.prepare() 的线程内创建处理程序”,但代码工作正常。

在 robolectric 中是否可以在没有弯针的情况下创建线程? 我也尝试过使用这个阴影:

@Implements(value = Looper.class, callThroughByDefault = true)
public static class EmptyLooper extends ShadowLooper {

    public static Looper myLooper() {
        return null;
    }
}

【问题讨论】:

    标签: android multithreading robolectric


    【解决方案1】:

    这对我有用。

    @RunWith(RobolectricTestRunner.class)
    @Config(manifest=Config.NONE, shadows={MyTest.EmptyLooper.class})
    public class MyTest {
        @Implements(value = Looper.class)
        public static class EmptyLooper extends ShadowLooper {
           @Implementation
           public static synchronized Looper myLooper() {
               if (Thread.currentThread() != getMainLooper().getThread()) return null;
               else return ShadowLooper.myLooper();
           }
       }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-01-25
      • 2017-10-07
      • 1970-01-01
      • 2017-01-27
      • 2021-07-23
      • 2014-11-05
      • 1970-01-01
      相关资源
      最近更新 更多