android - 如何授予对 android 仪器测试的权限?

标签 android android-studio testing permissions android-instrumentation

我有一个读取 SMS 的应用程序。该应用程序在调试时运行良好,但在使用 android 仪器测试对其进行测试时会抛出以下错误

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());
   }
}

我是仪器测试的新手。这是执行此操作的正确方法吗?

还是我遗漏了什么?

最佳答案

使用GrantPermissionRule .方法如下:

将以下依赖添加到app/build.gradle:

dependencies {
    ...
    androidTestImplementation 'androidx.test:rules:1.4.0'
}

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

import androidx.test.rule.GrantPermissionRule;

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

关于android - 如何授予对 android 仪器测试的权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50403128/

相关文章:

android - 显示导航栏后面的内容

android-studio - 如何在另一个 Activity 中使用一个 Activity 的 onActivityForResult

Android Studio 缺少初始分区文件 :

android - IdlingResources 无法运行 Espresso Android

testing - 如何在不等待测试的情况下在goroutine中测试结果

java - 使用 Maven 自动化测试构建过程

android - Android 中的多选下拉菜单

android - 将 ListView 更改为 ExpandableListView

testing - 网页横向滚动测试

java - Horizo​​ntalScrollView 和当前按钮