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.
I had the same issue. Creating a new thread within the test case seems to work.