IntentsTestRuleについて
IntentsTestRuleは、startActivity()でセットしたIntentのデータをテストすることができます。このクラスはActivityTestRuleを継承したクラスで、各Testの実行前にEspresso-Intentsを初期化し、実行後にEspresso-Intentsをリリースします。
各テスト後にActivityはfinish()されます。
build.gradleにEspresso-Intentsライブラリを追加します。
androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.1'
サンプルソース
次はユーザー操作によって、Intent.ACTION_CALLのIntentが発生したかどうかテストするサンプルプログラムです。@RunWith(AndroidJUnit4.class)
@LargeTest
public class MainActivityIntentTest {
@Rule
public IntentsTestRule<MainActivity> mActivityRule = new IntentsTestRule<>(
MainActivity.class);
@Before
public void stubAllExternalIntents() {
// By default Espresso Intents does not stub any Intents. Stubbing needs to be setup before
// every test run. In this case all external Intents will be blocked.
intending(not(isInternal()))
.respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, null));
}
@Test
public void callPhone() {
// call action
onView(withId(R.id.callButton)).perform(click());
// test
intended(allOf(
hasAction(Intent.ACTION_CALL),
hasData("tel:0123456789"),
toPackage("com.android.server.telecom")));
}
}
テストクラスは次のように作成します。- テストクラスにRunWithアノテーションをつける
- IntentsTestRuleを生成する、Ruleアノテーションをつける
Intentが発生したかどうかは、次のように判定します。
Activity起動時のIntentセット
テストを行うActivityの起動用Intentが必要な場合、IntentsTestRule#getActivityIntentメソッドをオーバーライドしてIntentを返す。
@Rule
public IntentsTestRule<MainActivity> mActivityRule = new IntentsTestRule<>(MainActivity.class) {
/**
* Activity起動用Intent
*/
@Override
protected Intent getActivityIntent() {
Intent intent = new Intent();
// Activity起動用のパラメータをセット
intent.putExtra(KEY_DATA,data);
return intent;
}
};
参考サイト:
https://github.com/googlesamples/android-testing