對不起,我查看了遍佈整個地方的教程,未找到我正在尋找的答案。我下面谷歌的教程,此刻在這裏: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();
}
我相信牛逼這是一個問題,因爲我沒有正確啓動服務或者什麼 - 我嘗試過使用幾種方法,但我只是隨處可見錯誤。在這裏搜索和這個錯誤是流行的,但不是與測試有關,所以想知道是否有人可以指出我在正確的方向,所以我可以測試這個類的方法?
Robolectric似乎不支持一些android事物,比如NotificationManager。結束了使用儀器測試,但花了我一段時間弄清楚了! –