您遇到的是正常行为,因为联系人选择器属于无法操作其用户界面的外部活动。试图断言任何东西都会导致测试停止一段时间并以
android.support.test.espresso.NoActivityResumedException:RESUMED阶段没有活动。您是否忘记启动活动。(test.getActivity() 或类似的)?
但是,向新生的Espresso-Intents打个招呼,这是为了挽救我的声誉:
使用预期 API(Mockito.when 的表亲),您可以为使用 startActivityForResult 启动的活动提供响应
更新
以下是我当前的解决方案,它工作正常,但需要一些体面的代码清理:
@Test
public void testContactPickerResult(){
Intent resultData = new Intent();
resultData.setData(getContactUriByName("Joah"));
Instrumentation.ActivityResult result = new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData);
intending(toPackage("com.google.android.contacts")).respondWith(result);
onView(withId(R.id.contactPickerLauncher))
.check(matches(isDisplayed()))
.perform(click());
onView(withId(R.id.pickedContact))
.check(matches(withText(getContactNumberByName("Joah"))));
}
在启动活动中,我将使用联系人 Uri 处理传入的意图,并对其进行任何必要的处理。
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
TextView result = (TextView) findViewById(R.id.pickedContact);
if (requestCode == 42 && resultCode == RESULT_OK){
Uri contactUri = data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursor cursor = getContentResolver().query(contactUri, projection, null, null, null);
cursor.moveToFirst();
int column = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
String number = cursor.getString(column);
result.setText(number);
}
}
此外,要相应修改的辅助方法:
public Uri getContactUriByName(String contactName) {
Cursor cursor = mActivityRule.getActivity().getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
if (name.equals(contactName)) {
return Uri.withAppendedPath(ContactsContract.Data.CONTENT_URI, id);
}
}
}
return null;
}