4
@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?

Daniel Wilson
  • 18,838
  • 12
  • 85
  • 135

1 Answers1

1

There are couple of solutions:

  1. Annotate the test with @UiThreadTest annotation from support library.

OR

  1. Call mLoginActivityTestRule.runOnUiThread to run only the portion of test on UI thread.

Hope one of those solutions solve your problem.

R. Zagórski
  • 20,020
  • 5
  • 65
  • 90