I use the android.os.Handler class to perform tasks on the background. When unit testing these, I call Looper.loop()
to make the test thread wait for the background task thread to do its thing. Later, I call Looper.myLooper().quit()
(also in the test thread), to allow the test thread to quit the loop
and resume the testing logic.
It's all fine and dandy until I want to write more than one test method.
The problem is that Looper doesn't seem to be designed to allow quitting and restarting on the same thread, so I am forced to do all of my testing inside a single test method.
I looked into the source code of Looper, and couldn't find a way around it.
Is there any other way to test my Hander/Looper code? Or maybe some more test friendly way to write my background task class?
The source code for Looper reveals that Looper.myLooper().quit() enqueues a null message in the Message queue, which tells Looper that it is done processing messages FOREVER. Essentially, the thread becomes a dead thread at that point, and there is no way to revive it that I know of. You may have seen error messages when attempting to post messages to the Handler after quit() is called to the effect "attempting to send message to dead thread". That is what that means.