我的测试文件如下所示:
@RunWith(AndroidJUnit4.class) @LargeTest public class CreateNewSessionActivityTest { @Rule public IntentsTestRulemActivityRule = 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); } } } }
我还在活动下面的Manifest中注册了Intent Filter.
活动中的代码也可以正常工作.如果我使用任何应用程序并与其共享文本,它将显示在EditText中.
但是这条线在测试中失败了:
onView(withId(R.id.create_new_session_auth_token_edit_text)).check(matches(withText("this is my auth token")));
文本根本不会显示在EditText中.我想测试Intent的方式有什么问题吗?
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.