Closed GoogleCodeExporter closed 9 years ago
Please see
https://code.google.com/p/android-test-kit/wiki/AndroidJUnitRunnerUserGuide#Inst
rumentation_Thread_Handlers
Basically the new AndroidJUnitRunner prevents any Handler from being created on
the Instrumentation worker thread. ActivityUnitTestCase.startActivity() needs
to be called on the main thread. There are several ways to do this:
1. Use Instrumentation's runOnMainSync()
getInstrumentation().runOnMainSync(new Runnable() {
@Override
public void run() {
activity = startActivity(new Intent(Intent.ACTION_MAIN), null, null);
}
});
2. Create your own base class that extends ActivityUnitTestCase<T extends
Activity> and override startActivity
@Override
protected T startActivity(final Intent intent, final Bundle savedInstanceState,
final Object lastNonConfigurationInstance) {
return startActivityOnMainThread(intent, savedInstanceState, lastNonConfigurationInstance);
}
private T startActivityOnMainThread(final Intent intent, final Bundle
savedInstanceState,
final Object lastNonConfigurationInstance) {
final AtomicReference<T> activityRef = new AtomicReference<>();
final Runnable activityRunnable = new Runnable() {
@Override
public void run() {
activityRef.set(YourBaseActivityUnitTestCase.super.startActivity(
intent, savedInstanceState, lastNonConfigurationInstance));
}
};
if (Looper.myLooper() != Looper.getMainLooper()) {
getInstrumentation().runOnMainSync(activityRunnable);
} else {
activityRunnable.run();
}
return activityRef.get();
}
You would extend your base test class instead of ActivityUnitTestCase directly
3. If you call startActivity() in a test method and your entire test can run on
the main thread, you can simply annotate your test method with @UiThreadTest.
Hope this helps.
Original comment by mhernan...@gmail.com
on 28 Jan 2015 at 7:24
Thank you very much for your response! You saved my day!
I tried all 3 techniques, from 3 > 1 > 2. At first, I was a bit bummed out
because 3 did not work. But luckily 1 & 2 was a success!
Thank you mhernan...!
Original comment by littledo...@gmail.com
on 6 Feb 2015 at 10:35
Anyone have success doing this with launchActivity as well?
Original comment by bi...@jana.com
on 4 Mar 2015 at 4:12
We are in the process of deprecating ActivityUnitTestCase. We recommend to move
business logic to a separate class and unit test it with gradle unit test
support (mockable android.jar).
Original comment by vale...@google.com
on 18 Mar 2015 at 5:22
Original comment by vale...@google.com
on 18 Mar 2015 at 5:23
Original issue reported on code.google.com by
littledo...@gmail.com
on 16 Jan 2015 at 7:31