android - Robolectric 3.0,未能测试启动 HandlerThread 的函数

标签 android unit-testing robolectric

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

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

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

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 类的 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 实例),或者我错过了什么?如何摆脱这个问题?

最佳答案

我遇到了类似的问题,不确定你的原因是否相同,因为我使用了 RobolectricGradleTestRunner 而你没有发布整个测试方法体。 在我的例子中,Robolectric 的应用程序 (RuntimeEnvironment.application) 在 HandlerThread 开始执行之前被设置为 null(NPE 的来源),因为测试方法提前结束。

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

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

关于android - Robolectric 3.0,未能测试启动 HandlerThread 的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34227018/

相关文章:

android - Robolectric 测试以检查是否显示 SnackBar?

java - 将使用 SOAP 从 (C# .net) Web 服务接收的对象转换为 Android 中的字符串数组

database - 需要上下文的 Android 单元测试

c# - 如果测试失败,TestCleanUp 中的条件行为

android - Robolectric 测试 Activity 创建,包括 Intent 附加功能

android - 如何调整 Robolectric 测试的屏幕密度?

android - 安装没有成功。无法安装应用程序。 java.io.IOException : Requested internal only, 但空间不足

android 始终运行应用程序,即使应用程序在后台

android - 通过代码访问 Android 4.3 中新的通知设置

java - 在模拟文件路径时如何编写有效的 JUnit 测试?