Daniel Wilson
Daniel Wilson

Reputation: 19834

Unit test including a Toast in production code fails

@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

Answers (1)

R. Zag&#243;rski
R. Zag&#243;rski

Reputation: 20268

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.

Upvotes: 1

Related Questions