自动权限请求Android检测测试

时间:2017-02-24 13:59:54

标签: android testing android-instrumentation

我正在进行我的第一次Android Instrumentation测试,其中一些测试需要Internet或写入外部存储的权限。遵循新的Marshmallow权限方式,我在AndroidManifest.xml中定义了这些权限,并在我的测试中定义了一条规则,如:

@Rule
public final PermissionsRule permissionsRule = new PermissionsRule(
        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE});

PermissionsRule是:

public class PermissionsRule implements TestRule {

    private final String[] permissions;

    public PermissionsRule(String[] permissions) {
        this.permissions = permissions;
    }

    @Override
    public Statement apply(final Statement base, Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {

                allowPermissions();

                base.evaluate();

                revokePermissions();
            }
        };
    }



    private void allowPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : permissions) {
                System.out.println("allowPermissions "+permission);
                getInstrumentation().getUiAutomation().executeShellCommand(
                        "pm grant " + InstrumentationRegistry.getTargetContext().getPackageName()
                                + " " + permission);
            }
        }
    }

    private void revokePermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            for (String permission : permissions) {
                getInstrumentation().getUiAutomation().executeShellCommand(
                        "pm revoke " + InstrumentationRegistry.getTargetContext().getPackageName()
                                + " " + permission);
            }
        }
    }
}

Internet权限运行正常,但写入或读取否。为什么呢?

0 个答案:

没有答案