2017-01-16 79 views
4
@Rule 
public ActivityTestRule<LoginTestActivity> mLoginActivityTestRule = new ActivityTestRule<>(LoginTestActivity.class); 

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

performLogin功能上面,当我通过应用程序运行正常工作正常,但是当我运行一个单元测试中我得到这个可怕的例外:单元测试,包括在生产代码举杯失败

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

错误行是我表现出吐司使用在主线程:

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

这是为什么失败,当我运行它作为一个单元测试?我猜ActivityTestRule以某种方式在它自己的线程上运行,它不被认为是Android的主线程。我该如何解决它?

我试过传递getInstrumentation().getTargetContext()作为Toa​​st的上下文,但是发生同样的错误。我是否应该将每个吐司显示包装在调用中以明确在UI线程上运行?

回答

0

有几个解决方案:

  1. 标注与支持库@UiThreadTest注释测试。

OR

  • 呼叫mLoginActivityTestRule.runOnUiThread仅运行于UI线程的测试部分上。
  • 希望这些解决方案之一解决您的问题。