Espresso And Android Contact Picker
Solution 1:
What you're experiencing is normal behavior, since the contact picker belongs to an external activity, whose user interface cannot be manipulated. Trying to assert anything will result in the tests stalling for some time and ending up with a
android.support.test.espresso.NoActivityResumedException: No activities in stage RESUMED. Did you forget to launch the activity. (test.getActivity() or similar)?
However, say hello to the new born Espresso-Intents, which is here to save my reputation:
Using the intending API (cousin of Mockito.when), you can provide a response for activities that are launched with startActivityForResult
UPDATE Below is my current solution which works fine but would need some decent code clean up:
@TestpublicvoidtestContactPickerResult(){
IntentresultData=newIntent();
resultData.setData(getContactUriByName("Joah"));
Instrumentation.ActivityResultresult=newInstrumentation.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"))));
}
In the launching activity, I would handle the incoming intent with the contact Uri and do whatever is necessary with it.
@OverrideprotectedvoidonActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
TextViewresult= (TextView) findViewById(R.id.pickedContact);
if (requestCode == 42 && resultCode == RESULT_OK){
UricontactUri= data.getData();
String[] projection = {ContactsContract.CommonDataKinds.Phone.NUMBER};
Cursorcursor= getContentResolver().query(contactUri, projection, null, null, null);
cursor.moveToFirst();
intcolumn= cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
Stringnumber= cursor.getString(column);
result.setText(number);
}
}
Also, the helper methods, to be modified accordingly:
publicUrigetContactUriByName(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)) {
returnUri.withAppendedPath(ContactsContract.Data.CONTENT_URI, id);
}
}
}
returnnull;
}
Post a Comment for "Espresso And Android Contact Picker"