我的测试文件如下所示:
@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")));
}
}在CreateNewSessionActivity.onCreate方法中,我执行以下操作:
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);
}
}
}
}我还在活动下面的清单中注册了意图过滤器。
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>活动中的代码也可以工作。如果我使用任何应用程序并与其共享文本,它将显示在EditText中。
但是,这一行在测试中失败:
onView(withId(R.id.create_new_session_auth_token_edit_text)).check(matches(withText("this is my auth token")));文本将完全不显示在EditText中。我想测试意图的方式有什么问题吗?
发布于 2016-01-06 04:49:35
intending是用来测试输出意图的。要测试传入意图,请使用带有第三个参数的ActivityRule作为false。
@Rule
public ActivityTestRule activityRule = new ActivityTestRule<>(
CreateNewSessionActivity.class,
true, // initialTouchMode
false); // launchActivity. False to set intent.然后以这样的方式展开你的活动:
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);有关更多信息,请参见http://blog.sqisland.com/2015/04/espresso-21-activitytestrule.html。
https://stackoverflow.com/questions/34617411
复制相似问题