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

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

问题描述

我有一个读取SMS的应用程序.该应用在调试时可以正常运行,但在使用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天全站免登陆