Then I use actual Java JUnit and Robolectric to test my code, but the problem of this approach is some code that is need to be ran inside Android environment cannot actually running while testing.
In my case, I use Handler from background Thread to sends Message back to caller Thread. I want to test that the callback method is actually executed on caller Thread but the Message is never be sent in testing because of the test environment.
Here is snippet of my TargetClass code.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
From the code above, the background Thread (HandlerThread ht) will send Message to mCallbackHandler which will force caller Thread to execute handleMessage() and execute mListener.onSuccess().
While test is running, the callback method onSuccess() won't be executed because the Message cannot be sent in testing environment.
So, instead of validate test result in onSuccess() (which cannot be reached here), I change to validate Handler object.
Here is snippet from my test code.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
At the third step, I get the Handler object from target class and wrap it inside Robolectric's ShadowHandler. Then validate the Message that the handler contains and the Thread id that associated with its Looper.
If these test cases are passed, then I can guarantee that the TargetClass will execute the right callback on the right Thread.
It's something, isn't it? :-)








