My test focuses on shutting down AsyncTask and verifying that the next action will run.
It is known that AsyncTask # onPostExecute is not called if AsyncTask is not created and executed from the user interface thread, so my (test visible) method for calling AsyncTask takes the necessary precautions to ensure this behavior - through Runnable, which runs immediately if the thread UI or scheduled to run in the UI thread.
When this method is called from the ActivityUnitTestCase test, Runnable, which creates and runs this AsyncTask through Activity # runOnUiThread, starts in a thread other than the user interface thread. Is there a way to guarantee that this Runnable will execute in the user interface thread from Activity?
Addenda:
- The test runs as expected in the ActivityInstrumentationTestCase2 class, but I do not have access to the ActivityUnitTestCase # getStartedActivityIntent. I know about Instrumentation.ActivityMonitor and this is not a solution.
- Runnables scheduled on ActivityUnitTestCase # runTestOnUiThread do run in the user interface. a thread.
- I do not want to redefine my test.
- Oddly enough, ActivityUnitTestCase # startActivity calls Activity # onCreate NOT in the UI thread.
Edit: here is some (unverified) code that demonstrates the essence of the problem:
// ExampleActivityTests.java class ExampleActivityTests : public ActivityUnitTestCase <ExampleActivity> { public void testThatRequiresUiThread() { startActivity (new Intent(), null, null); // ...call instrumentation onStart, onResume... runTestOnUiThread(new Runnable() { public void run() { boolean isUiThread = Thread.currentThread() == Looper.getMainLooper().getThread(); Log.d ("A", "Running on UI Thread? " + isUiThread); } }); getActivity().methodRequiringUiThread(); // assertions here... } } // ExampleActivity.java -- just the relevant method public void methodRequiringUiThread() { runOnUiThread(new Runnable() { public void run() { boolean isUiThread = Thread.currentThread() == Looper.getMainLooper().getThread(); Log.d ("B", "Running on UI Thread? " + isUiThread); } }); }
In LogCat we will see:
A | Running on UI Thread? true B | Running on UI Thread? false
source share