在我的Android应用程序中,我需要测试编辑片段,能够从Android联系人中选择联系人。
我的问题是:是否有方法在Android espresso测试之前创建联系人并且在清单中没有WRITE_CONTACTS权限?或者我可以以某种方式模拟内容解析器吗?
以下是我如何联系的代码:
@OnClick(R.id.et_contact)
void chooseContactClick(View v) {
launchContactPicker(v);
}
public void launchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
private ContactInf fetchPersonFromIntent(Intent data) {
ContactInf contactInf = null;
Uri uri = data.getData();
ContentResolver cr = getActivity().getContentResolver();
Cursor contentCursor = cr.query(uri, null, null,null, null);
if(contentCursor.moveToFirst()) {
String id = contentCursor.getString(contentCursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
// Perform a query to retrieve the contact's name parts
String[] nameProjection = new String[] {
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME,
ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME
};
Cursor nameCursor = cr.query(
ContactsContract.Data.CONTENT_URI,
nameProjection,
ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID
+ "=?", new String[]{id}, null);
// Retrieve the name parts
String firstName = StringUtils.EMPTY, middleName = StringUtils.EMPTY, lastName = StringUtils.EMPTY;
if(nameCursor.moveToNext()) {
firstName = nameCursor.getString(nameCursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME));
middleName = nameCursor.getString(nameCursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME));
lastName = nameCursor.getString(nameCursor.getColumnIndex(
ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME));
String msg = String.format(" contact %s %s %s %s ", id, firstName, middleName, lastName);
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
try {
long idLong = Long.valueOf(id);
contactInf = new ContactInf(idLong, firstName, middleName, lastName);
} catch (NumberFormatException e) {
Log.e(TAG, String.format(" NumberFormatException during parse id [%s] ", id));
}
}
}
return contactInf;
}
谢谢!
答案 0 :(得分:0)
我通过在src \ debug \文件夹中添加一个清单文件解决了我的问题:uses-permission android:name =“android.permission.WRITE_CONTACTS”
在这种情况下,我有调试的WRITE_CONTACTS权限,没有按预期发布它。