2017-09-27 9 views
0

申し訳ありません私はチュートリアルを全面的に見て、私が探している答えが見つかりませんでした。私はここで、現時点では、Googleのチュートリアルを次のようだ:https://developer.android.com/training/testing/unit-testing/instrumented-unit-tests.html計装ユニットクラステスト - Looper.prepare()を呼び出していないスレッド内でハンドラを作成できません。

を私は計装テストを作成しようとしていると私はそれを実行すると、私はエラーを取得しています:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

次のようにだから私のテストは次のとおりです。

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(); 
    } 

私はトンを推測:

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")); 
    } 
} 

そして、私がメインの活動があるの内側に次のようにメソッドを実行しようとしている(これは、抽出物です)帽子これは問題です。サービスを正しく起動していないからです。何通りか試してみましたが、どこでもエラーが出ます。ここでの検索とこのエラーは一般的ですが、テストとの関連ではないので、誰かが私を正しい方向に向けることができたら、このクラスのメソッドをテストできますか?

答えて

1

Looperがテスト対象システム(MainActivity)に正しく設定されていないため、エラーが発生しています。

ActivityFragmentなどが引数なしのコンストラクタを持っていますが、彼らはAndroidのOSによってインスタンス化されるように設計された、そのようにMainActivity = new Activity()を呼び出すことHandlerLooperと完全フル稼働 死の星 インスタンスを取得するだけでは十分ではないされています。

あなたがテストを続行したい場合は2つのオプションがあります。

  1. あなたは活動の実際のインスタンスをテストする場合、それはinstrumented unit testandroidTestないtest)と@TestRule意志なければならないだろうあなたはを使用することができますIDEで実行するローカルユニットテストを書いておくことを好むだろう場合

    @Rule 
    public ActivityTestRule<MainActivity> mActivityRule = 
        new ActivityTestRule(MainActivity.class); 
    
  2. :正しく活動のインスタンスをインスタンス化するには、Android OSを引き起こします。 Robolectricは、Looperなどに依存するコンポーネントをテストできるように、シャドウアクティビティで正しく動作をスタブします。いくつかの設定が含まれていることに注意してください。

+0

Robolectricは、NotificationManagerのようないくつかのアンドロイドのものをサポートしていないようでした。インストゥルメンテッドテストを使用して終了しましたが、それを理解するまでには時間がかかりました。 –

関連する問題