Unit test, including toast in production code, doesn't work

@Rule
public ActivityTestRule<LoginTestActivity> mLoginActivityTestRule = new ActivityTestRule<>(LoginTestActivity.class);

@Test
public void loginWithTwitter() throws Exception
{
    mLoginActivityTestRule.getActivity().performLogin();
}

The function performLoginabove works fine when I usually run the application, but when I run it inside the unit test, I get this terrible exception:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

The error line is where I show Toast in the main thread using:

Toast.makeText(getApplicationContext(), "Login Success!", Toast.LENGTH_LONG).show();

Why does this happen when I run it as a unit test? I assume that the ActivityTestRule runs its own thread on it, and it is not considered the main thread for Android. How can I solve it?

I tried passing in getInstrumentation().getTargetContext()for use as a context for Toast, but the same error occurs. Do I have to wrap every display of the toast in the call to execute in the user interface thread explicitly?

+4
1

:

  • @UiThreadTest .

  1. mLoginActivityTestRule.runOnUiThread .

, .

0

Source: https://habr.com/ru/post/1666905/


All Articles