LoginSignup
19
15

More than 5 years have passed since last update.

espresso-intentsでIntentをテストする

Last updated at Posted at 2015-08-16

つい最近Androidのテストを書き始めた素人です。
espresso-intentsでIntentをテストする方法を調べました。

espresso-intentsの設定

他の記事ともかぶりますが、espressoの設定。

build.gradle
android {
    ...
    defaultConfig {
        ...
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    packagingOptions {
        exclude 'LICENSE.txt'
    }
}
dependencies {
    ...
    androidTestCompile 'com.android.support:support-annotations:22.2.1'
    androidTestCompile('com.android.support.test:runner:0.3'){
        exclude module: 'support-annotations'
    }
    androidTestCompile ('com.android.support.test:rules:0.3'){
        exclude module: 'support-annotations'
    }
    androidTestCompile ('com.android.support.test.espresso:espresso-core:2.2'){
        exclude module: 'support-annotations'
    }
    androidTestCompile ('com.android.support.test.espresso:espresso-intents:2.2'){
        exclude module: 'support-annotations'
    }
}

※support-annotaions のexcludeはバージョンによって不要かも。

テスト対象のコード

MainActivity.java
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button1 = (Button)findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SubActivity.class );
                intent.putExtra("param","test");
                startActivity(intent);
            }
        });

        Button button2 = (Button)findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SubActivity2.class );
                startActivityForResult(intent, 100);
            }
        });

        Intent intent = getIntent();
        String param = intent.getStringExtra("param");
        TextView textView = (TextView)findViewById(R.id.textView);
        textView.setText(param);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ( resultCode == RESULT_OK && requestCode == 100 ){
            String result = data.getStringExtra("result");
            TextView textView = (TextView)findViewById(R.id.textView);
            textView.setText(result);
        }
    }
}

機能は三つ。
1. ボタン1を押すとEXTRA付きIntentを投げて、SubActivityを開く。
2. ボタン2を押すとSubActivity2を forResultで呼び出す。
3. 起動時のIntentからEXTRAを読み込んで、テキストビューに設定。

テストコード

MainActivityTest.java
@RunWith(AndroidJUnit4.class)
public class MainActivityTest extends ActivityInstrumentationTestCase2<MainActivity> {

    public MainActivityTest() {
        super(MainActivity.class);
    }

    @Rule
    public IntentsTestRule<MainActivity> mActivityRule = new IntentsTestRule<>(MainActivity.class);

    @Before
    public void setUp() throws Exception {
        super.setUp();
        injectInstrumentation(InstrumentationRegistry.getInstrumentation());
    }

    @After
    public void tearDown() throws Exception {
        super.tearDown();
    }

    @Test
    public void testテスト1() {
        // ボタンをクリック
        onView(withId(R.id.button1)).perform(click());

        // startActivityのIntentの内容をチェックする
        intended(allOf(
                hasComponent(hasMyPackageName()),
                hasComponent(hasClassName("jp.gr.aqua.sampletestapp.SubActivity")),
                hasExtra("param", "test")
        ));
    }

    @Test
    public void testテスト2() {

        // ActivityResultで変える予定の値を事前に設定しておく
        Intent resultData = new Intent();
        resultData.putExtra("result", "test result");
        Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
        intending(toPackage("jp.gr.aqua.sampletestapp")).respondWith(result);

        // その後、ボタンをクリック
        onView(withId(R.id.button2)).perform(click());

        // 出力されるIntentをテスト
        intended(allOf(
                hasComponent(hasMyPackageName()),
                hasComponent(hasClassName("jp.gr.aqua.sampletestapp.SubActivity2"))
        ));

        // Resultが反映されたかテスト
        onView(withId(R.id.textView)).check(matches(withText("test result")));
    }

    @Test
    public void testテスト3() {
        // 起動Intentのパラメータを設定する
        Intents.release();
        Intent intent = new Intent();
        intent.putExtra("param", "initial-data");
        mActivityRule.launchActivity(intent);

        // パラメータが反映されているかテスト
        onView(withId(R.id.textView)).check(matches(withText("initial-data")));
    }
}

確認項目

hasHogeHoge() とかは、IntentMatcherのリファレンスを見てコピペしてから、自動補完でstatic import method ...でimportを追加するという手順になります。
Matcherをどう組み合わせるかは、数書いて慣れていくしかなさそうです。

教えてえらい人

setResult()につけたIntentをテスト出来るとありがたいのですが、分かりませんでした。Espresso難しい。

参考にしたサイト

以上です。

19
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
15