在浓缩咖啡测试前建立联系

Create contact before espresso test

在我的 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;
}

谢谢!

我通过将另一个清单文件添加到 src\debug\ 文件夹中解决了我的问题:uses-permission android:name="android.permission.WRITE_CONTACTS"

在这种情况下,我有 WRITE_CONTACTS 调试权限,但没有按预期发布。