IntentsTestRuleについて
IntentsTestRuleは、startActivity()でセットしたIntentのデータをテストすることができます。このクラスはActivityTestRuleを継承したクラスで、各Testの実行前にEspresso-Intentsを初期化し、実行後にEspresso-Intentsをリリースします。
各テスト後にActivityはfinish()されます。
build.gradleにEspresso-Intentsライブラリを追加します。
1 | androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.1' |
サンプルソース
次はユーザー操作によって、Intent.ACTION_CALLのIntentが発生したかどうかテストするサンプルプログラムです。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | @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を返す。1 2 3 4 5 6 7 8 9 10 11 12 13 14 | @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