如何授予 android 仪器测试的权限? [英] How to grant permissions to android instrumented tests?

查看:41
本文介绍了如何授予 android 仪器测试的权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以读取短信的应用程序.该应用程序在调试时运行良好,但在使用 android 检测测试时,它会引发以下错误

I have an application that reads SMSs. The app works fine when debugging but when testing it using android instrumented test it throws the following error

java.lang.SecurityException: Permission Denial: reading com.android.providers.telephony.SmsProvider

这是我的测试用例

@RunWith(AndroidJUnit4.class)
public class SmsFetcherTest {

   @Test
   public void fetchTenSms() throws Exception {
      // Context of the app under test.
      Context appContext = InstrumentationRegistry.getContext();

      //   Fails anyway.
      //   assertTrue(ContextCompat.checkSelfPermission(appContext,
      //     "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED);

      List<Sms> tenSms = new SmsFetcher(appContext)
              .limit(10)
              .get();

      assertEquals(10, tenSms.size());
   }
}

我是仪器测试的新手.这是正确的方法吗?

I'm new to instrumented tests. Is this is proper way to do this?

还是我遗漏了什么?

推荐答案

使用 GrantPermissionRule.方法如下:

Use GrantPermissionRule. Here's how:

app/build.gradle中添加如下依赖:

dependencies {
    ...
    androidTestImplementation 'com.android.support.test:rules:1.0.2'
}

现在将以下内容添加到您的 InstrumentedTest 类:

Now add the following to your InstrumentedTest class:

import androidx.test.rule.GrantPermissionRule;

public class InstrumentedTest {
    @Rule
    public GrantPermissionRule mRuntimePermissionRule = GrantPermissionRule.grant(Manifest.permission.READ_SMS);
    ...
}

这篇关于如何授予 android 仪器测试的权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆