2017-01-16 88 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線程的測試部分上。
  • 希望這些解決方案之一解決您的問題。