I have a simple class Job
which extends HandlerThread:
public class Job extends HandlerThread{
public Job(String name) {
super(name);
}
...
}
Then, I have a JobUtils
class which has a function to get a Job
& start()
it:
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();
}
}
I use Robolectric 3.0 in my unit test, I test JobUtils
class’ getAndStartJob(String name)
function :
@RunWith(RobolectricTestRunner.class)
public class TestJobUtils{
@Test
public void testGetAndStartJob() {
JobUtils jobUtils = new JobUtils();
// error here
jobUtils.getAndStartJob(“test-job”);
…
}
}
When I run my unit test code, I got the error
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)
It looks like Robolectric is not able to start the HandlerThread
(the job
instace in my code), or do I miss something? How to get rid of this problem?
I faced similar issue, not sure if your reason is the same because I used RobolectricGradleTestRunner
and you have not posted whole test method body.
In my case it turns out that Robolectric's application (RuntimeEnvironment.application
) is set to null
(source of NPE) before HandlerThread
starts executing because test method reaches the end earlier.
Workaround is to wait for all scheduled runnables at the end of test method:
Robolectric.flushBackgroundThreadScheduler();
Robolectric.flushForegroundThreadScheduler();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With