* Rules are interceptors which are executed for each test method and will run before * any of your setup code in the {@link Before @Before} method. *
* This rule is based on {@link ActivityTestRule} and will create and launch of the activity * for you and also expose the activity under test. */ @Rule public IntentsTestRule mActivityRule = new IntentsTestRule<>( DialerActivity.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 ActivityResult(Activity.RESULT_OK, null)); } @Before public void grantPhonePermission() { // In M+, trying to call a number will trigger a runtime dialog. Make sure // the permission is granted before running this test. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { getInstrumentation().getUiAutomation().executeShellCommand( "pm grant " + getTargetContext().getPackageName() + " android.permission.CALL_PHONE"); } } @Test public void typeNumber_ValidInput_InitiatesCall() { // Types a phone number into the dialer edit text field and presses the call button. onView(withId(R.id.edit_text_caller_number)) .perform(typeText(VALID_PHONE_NUMBER), closeSoftKeyboard()); onView(withId(R.id.button_call_number)).perform(click()); // Verify that an intent to the dialer was sent with the correct action, phone // number and package. Think of Intents intended API as the equivalent to Mockito's verify. intended(allOf( hasAction(Intent.ACTION_CALL), hasData(INTENT_DATA_PHONE_NUMBER), toPackage(PACKAGE_ANDROID_DIALER))); } @Test public void pickContactButton_click_SelectsPhoneNumber() { // Stub all Intents to ContactsActivity to return VALID_PHONE_NUMBER. Note that the Activity // is never launched and result is stubbed. intending(hasComponent(hasShortClassName(".ContactsActivity"))) .respondWith(new ActivityResult(Activity.RESULT_OK, ContactsActivity.createResultData(VALID_PHONE_NUMBER))); // Click the pick contact button. onView(withId(R.id.button_pick_contact)).perform(click()); // Check that the number is displayed in the UI. onView(withId(R.id.edit_text_caller_number)) .check(matches(withText(VALID_PHONE_NUMBER))); } }