【问题标题】:Robolectric 3.0 , failed to test a function which starts a HandlerThreadRobolectric 3.0,未能测试启动 HandlerThread 的函数
【发布时间】:2015-12-11 15:30:32
【问题描述】:

我有一个简单的类Job,它扩展了HandlerThread

public class Job extends HandlerThread{
  public Job(String name) {
     super(name);
  }
  ...
}

然后,我有一个JobUtils 类,它具有获取Jobstart() 它的功能:

public JobUtils {
   public JobUtils() {
   }

   // I unit test this function in my test class below
   public Job getAndStartJob(String name) {
      Job job = new Job(name);
      job.start();
   }
}

我在单元测试中使用Robolectric 3.0,我测试JobUtils class'getAndStartJob(String name)函数:

@RunWith(RobolectricTestRunner.class)
public class TestJobUtils{
 @Test
 public void testGetAndStartJob() {
    JobUtils jobUtils = new JobUtils();

    // error here
    jobUtils.getAndStartJob(“test-job”);
    …
 }
}

当我运行我的单元测试代码时,我得到了错误

Exception in thread "test-job” java.lang.NullPointerException
    at org.robolectric.shadows.ShadowLooper.getMainLooper(ShadowLooper.java:70)
    at org.robolectric.shadows.ShadowLooper.doLoop(ShadowLooper.java:85)
    at org.robolectric.shadows.ShadowLooper.loop(ShadowLooper.java:76)
    at android.os.Looper.loop(Looper.java)
    at android.os.HandlerThread.run(HandlerThread.java:60)

看起来 Robolectric 无法启动 HandlerThread(我的代码中的 job 实例),还是我错过了什么?如何摆脱这个问题?

【问题讨论】:

    标签: android unit-testing robolectric


    【解决方案1】:

    我遇到了类似的问题,不确定您的原因是否相同,因为我使用了RobolectricGradleTestRunner,而您还没有发布整个测试方法主体。 就我而言,事实证明 Robolectric 的应用程序 (RuntimeEnvironment.application) 在 HandlerThread 开始执行之前被设置为 null(NPE 的来源),因为测试方法更早地到达终点。

    解决方法是在测试方法结束时等待所有计划的可运行:

        Robolectric.flushBackgroundThreadScheduler();
        Robolectric.flushForegroundThreadScheduler();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 2013-08-04
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      相关资源
      最近更新 更多