Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Robolectric 3.0 , failed to test a function which starts a HandlerThread

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?

like image 491
Leem.fin Avatar asked Dec 11 '15 15:12

Leem.fin


1 Answers

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();
like image 114
koral Avatar answered Oct 19 '22 09:10

koral