Android Espresso Intent

2019-04-13 14:30发布

问题:

My test file looks like this:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class CreateNewSessionActivityTest {
    @Rule
    public IntentsTestRule<CreateNewSessionActivity> mActivityRule = new IntentsTestRule<>(CreateNewSessionActivity.class);

    @Test
    public void test() {
        final Intent intent = new Intent();
        intent.setAction(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_TEXT, "this is my auth token");

        final Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, intent);

        intending(hasComponent(hasShortClassName(".CreateNewSessionActivity"))).respondWith(result);

        onView(withId(R.id.create_new_session_auth_token_edit_text)).check(matches(isDisplayed()));
        onView(withId(R.id.create_new_session_auth_token_edit_text)).check(matches(withText("this is my auth token")));
    }
}

In the CreateNewSessionActivity.onCreate method I execute the following:

final Intent intent = this.getIntent();

if (intent != null) {
    final String action = intent.getAction();
    final String type = intent.getType();

    if (Intent.ACTION_SEND.equals(action) && type != null) {
        if ("text/plain".equals(type)) {
            final String sharedText = intent.getStringExtra(Intent.EXTRA_TEXT);

            if (sharedText != null) {
                authTokenEditText.setText(sharedText);
            }
        }
    }
}

I also registered the Intent Filter in the Manifest underneath the activity.

<intent-filter>
    <action android:name="android.intent.action.SEND"/>
    <category android:name="android.intent.category.DEFAULT"/>
    <data android:mimeType="text/plain"/>
</intent-filter>

The code in the activity also does work. If I use any app and share text to it it'll be displayed in the EditText.

However this line fails in the test:

onView(withId(R.id.create_new_session_auth_token_edit_text)).check(matches(withText("this is my auth token")));

The text won't be displayed in the EditText at all. Is there anything wrong with the way I want to test the Intent?

回答1:

intending is for testing outgoing intents. To test incoming intent, use an ActivityRule with the third argument as false.

@Rule
public ActivityTestRule activityRule = new ActivityTestRule<>(
    CreateNewSessionActivity.class,
    true,    // initialTouchMode
    false);  // launchActivity. False to set intent.

Then launch your activity this way:

Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "this is my auth token");
activityRule.launchActivity(intent);

See http://blog.sqisland.com/2015/04/espresso-21-activitytestrule.html for more info.