Creating a new Handler on the main thread in ApplicationTestCase

521 views Asked by At

In my Instrumentation Tests, I have a base class that extends ApplicationTestCase<TestApplication> TestApplication extends Application and just does some basic init work in onCreate().

In one test suite, I am testing a class that instantiates a new Handler, via the new Handler(); call. This compiles and runs fine in the application, however, in the tests always fails with:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

in the Application class, calling:

 @Override
    public void onCreate() {
        super.onCreate();
        this.getMainLooper().prepare();
  }

doesn't help either as the first test runs fine, and subsequent tests fail with

java.lang.RuntimeException: Only one Looper may be created per thread

and calling this.getMainLooper().quit() or this.getMainLooper().quitSafely() in onTerminate() as it seems the same thread is used for all the tests run in the suite (also causing the above issue) so it errors for all tests because of the issues quitting the Looper on a live thread.

I can get around this by using a static boolean flag to only run prepare() once, but this just seems incredibly janky. Should I submit a bug, or is there something in the code that is being done wrong?

Appreciate the help in advance.

1

There are 1 answers

0
tobiasfuenkejr On

I had the same issue. Creating a new thread within the test case seems to work.

final CountDownLatch latch = new CountDownLatch(1);
new Thread() {
    @Override
    public void run() {
        Looper.prepare();
        // ...
        // Your code here
        // ...
        latch.countDown();
    }
}.start();
latch.await();
assertTrue("Failed to run thread for test", latch.getCount() == 0);