トラッキング コード

4/29/2015

How to IntentsTestRule, in AndroidTest




About IntentsTestRule

IntentsTestRule is AndroidTest which can do intent test.

If use, we have to add Espresso-Intents library in build.gradle.
    androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.1'

Test Sample

The following code is sample which Intent has Intent.ACTION_CALL by user operation.
@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")));

    }
}
How to create test class.
  • create test class with RunWith annotation
  • add IntentsTestRule with Rule annotation

We can check whether Intent has occurred.
  • Intended method which check the intended Intent
  • matches method


  • Add Intent to Starting Activity

    If need to add Intent to Activity, we need to do override IntentsTestRule#getActivityIntent.
        @Rule
        public IntentsTestRule<MainActivity> mActivityRule = new IntentsTestRule<>(MainActivity.class) {
    
            /**
            * add Intent to Activity
            */
            @Override
            protected Intent getActivityIntent() {
                Intent intent = new Intent();
                intent.putExtra(KEY_DATA,data);
                return intent;
            }
        };
    

    https://github.com/googlesamples/android-testing