LoginSignup
6
3

More than 3 years have passed since last update.

EspressoテストでActivity起動Intentにパラメータを追加したい

Last updated at Posted at 2016-05-09

全てのテストで同じパラメータを使いたい場合

ActivityTestRuleのgetActivityIntentをオーバーライドする

HogeActivityTest.java
public class HogeActivityTest {
    @Rule
    public ActivityTestRule<HogeActivity> mActivityRule = new ActivityTestRule<HogeActivity>(
            HogeActivity.class) {
        @Override
        public Intent getActivityIntent() {
            Intent intent = new Intent();
            intent.putExtra("param1", 1);
            intent.putExtra("param2", "2");
            return intent;
        }
    };

テスト毎にパラメータを変更したい場合

ActivityTestRuleのパラメータ3つのコンストラクタを使用する
ドキュメントを確認すると、第3引数が自動でActivityを起動するフラグになっており、falseを設定することで
テスト毎に異なるパラメータを渡して起動することができる。

HogeActivityTest.java
    @Rule
    public ActivityTestRule<HogeActivity> mActivityRule = new ActivityTestRule<HogeActivity>(
            HogeActivity.class, false, false);

    @Test
    public void test1() {
        Intent intent = new Intent();
        intent.putExtra("param1", 1);
        intent.putExtra("param2", "1");
        mActivityRule.launchActivity(intent);
    }

    @Test
    public void test2() {
        Intent intent = new Intent();
        intent.putExtra("param1", 2);
        intent.putExtra("param2", "2");
        mActivityRule.launchActivity(intent);
    }

起動対象のActivity情報は、ActivityTestRule#launchActivityの中でセットされるので自分でセットする必要はない

まれに@Beforeアノテーションをつけたメソッド内でActivityを起動しているサンプルを見かけるが、
これでは、パラメータをテスト毎に変更できない。

参考:http://developer.android.com/intl/ja/reference/android/support/test/rule/ActivityTestRule.html

6
3
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
6
3