2017-09-27 18 views
0

對不起,我查看了遍佈整個地方的教程,未找到我正在尋找的答案。我下面谷歌的教程,此刻在這裏:https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.htmlInstrumented Unit Class Test - 無法在未調用Looper.prepare()的線程中創建處理程序

我試圖創建一個儀器化試驗,當我運行它,我發現了錯誤:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

所以我的測試如下:

package testapp.silencertestapp; 

import android.support.test.filters.SmallTest; 
import android.support.test.runner.AndroidJUnit4; 

import org.junit.Before; 
import org.junit.Test; 
import org.junit.runner.RunWith; 

import static org.hamcrest.Matchers.is; 
import static org.junit.Assert.assertThat; 

@RunWith(AndroidJUnit4.class) 
@SmallTest 
public class MainActivityTest { 

    private MainActivity testMain; 

    @Before 
    public void createActivity(){ 
     testMain = new MainActivity(); 
    } 

    @Test 
    public void checkFancyStuff(){ 
     String time = testMain.createFancyTime(735); 

     assertThat(time, is("07:35")); 
    } 
} 

而且我試圖運行的方法中的主要活動如下(這是一個摘錄):

public class MainActivity extends AppCompatActivity { 

    private TimePicker start; 
    private TimePicker end; 

@Override 
    protected void onCreate(Bundle savedInstanceState) { 
     start = (TimePicker) findViewById(R.id.startPicker); 
     end = (TimePicker) findViewById(R.id.endPicker); 
} 

String createFancyTime(int combinedTime) { 

     StringBuilder tempString = new StringBuilder(Integer.toString(combinedTime)); 
     if(tempString.length()==4){ 
      tempString = tempString.insert(2, ":"); 
     } 
     else if (tempString.length()==3){ 
      tempString = tempString.insert(1, ":"); 
      tempString = tempString.insert(0, "0"); 
     } 
     else if(tempString.length()==2){ 
      tempString = tempString.insert(0, "00:"); 
     } 
     else if(tempString.length()==1){ 
      tempString = tempString.insert(0, "00:0"); 
     } 
     return tempString.toString(); 
    } 

我相信牛逼這是一個問題,因爲我沒有正確啓動服務或者什麼 - 我嘗試過使用幾種方法,但我只是隨處可見錯誤。在這裏搜索和這個錯誤是流行的,但不是與測試有關,所以想知道是否有人可以指出我在正確的方向,所以我可以測試這個類的方法?

回答

1

由於您的系統(MainActivity)未正確設置Looper而出現錯誤。

雖然ActivityFragment等無參數的構造,它們被設計成由Android操作系統,因此調用MainActivity = new Activity()不足以獲得全業務 殺星 實例完成HandlerLooper被實例化。

有兩種選擇,如果你想測試繼續:

  1. 如果你想測試一個活動的實際情況,將必須是一個instrumented unit testandroidTesttest)和@TestRule會導致Android操作系統正確實例化活動的一個實例:

    @Rule 
    public ActivityTestRule<MainActivity> mActivityRule = 
        new ActivityTestRule(MainActivity.class); 
    
  2. 如果你希望保持編寫在IDE中運行,您可以使用本地單元測試。 Robolectric將正確地將行爲存儲在陰影活動中,以便您可以測試依賴於Looper等的組件。請注意,有一些設置涉及到。

+0

Robolectric似乎不支持一些android事物,比如NotificationManager。結束了使用儀器測試,但花了我一段時間弄清楚了! –

相關問題