Lee*_*fin 14 android unit-testing robolectric
我有一个Job扩展HandlerThread的简单类:
public class Job extends HandlerThread{
public Job(String name) {
super(name);
}
...
}
Run Code Online (Sandbox Code Playgroud)
然后,我有一个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();
}
}
Run Code Online (Sandbox Code Playgroud)
我在单元测试中使用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”);
…
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行我的单元测试代码时,我收到了错误
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)
Run Code Online (Sandbox Code Playgroud)
看起来Robolectric无法启动HandlerThread(job我的代码中的实例),还是我错过了什么?如何摆脱这个问题?
我遇到了类似的问题,不确定你的原因是否相同,因为我使用了RobolectricGradleTestRunner并且你没有发布整个测试方法主体。就我而言,事实证明,Robolectric 的应用程序 ( RuntimeEnvironment.application) 在开始执行之前设置为null(NPE 的来源)HandlerThread,因为测试方法较早到达末尾。
解决方法是在测试方法结束时等待所有计划的可运行对象:
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
916 次 |
| 最近记录: |