我有一个读取 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/