Reputation: 19834
@Rule
public ActivityTestRule<LoginTestActivity> mLoginActivityTestRule = new ActivityTestRule<>(LoginTestActivity.class);
@Test
public void loginWithTwitter() throws Exception
{
mLoginActivityTestRule.getActivity().performLogin();
}
The performLogin
function above works fine when I run through the app normally, but when I run it inside a unit test I get this dreaded exception:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
The error line is where I show a Toast on the main thread using:
Toast.makeText(getApplicationContext(), "Login Success!", Toast.LENGTH_LONG).show();
Why is this failing when I run it as a unit test? I guess an ActivityTestRule runs on it's own thread somehow, and it is not considered the main thread by Android. How can I resolve it?
I have tried passing in getInstrumentation().getTargetContext()
to use as the context for the Toast but the same error occurs. Should I wrap every toast display in a call to run on the UI thread explicitly?
Upvotes: 4
Views: 479
Reputation: 20268
There are couple of solutions:
@UiThreadTest
annotation from support library.OR
mLoginActivityTestRule.runOnUiThread
to run only the portion of test on UI thread.Hope one of those solutions solve your problem.
Upvotes: 1