[英]How to grant permissions to android instrumented tests?
I have an application that reads SMSs.我有一个读取 SMS 的应用程序。 The app works fine when debugging but when testing it using android instrumented test it throws the following error该应用程序在调试时运行良好,但在使用 android 仪器测试对其进行测试时会抛出以下错误
java.lang.SecurityException: Permission Denial: reading com.android.providers.telephony.SmsProvider
This is my test case这是我的测试用例
@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?这是执行此操作的正确方法吗?
Or am I missing something?或者我错过了什么?
Use GrantPermissionRule
. 使用GrantPermissionRule
。 Here's how: 这是如何做:
Add the following dependency to app/build.gradle
: 将以下依赖项添加到app/build.gradle
:
dependencies {
...
androidTestImplementation 'com.android.support.test:rules:1.0.2'
}
Now add the following to your InstrumentedTest
class: 现在将以下内容添加到InstrumentedTest
类:
import androidx.test.rule.GrantPermissionRule;
public class InstrumentedTest {
@Rule
public GrantPermissionRule mRuntimePermissionRule = GrantPermissionRule.grant(Manifest.permission.READ_SMS);
...
}
You can grant the permission as follows: 您可以按如下方式授予权限:
@RunWith(AndroidJUnit4.class)
public class MyInstrumentationTest {
@Rule
public GrantPermissionRule permissionRule = GrantPermissionRule.grant(Manifest.permission.READ_SMS);
...
}
If you use inheritance for instrumentation classes you should write @get:Rule
in parent class.如果您将 inheritance 用于检测类,则应在父级 class 中编写@get:Rule
。
For location:对于位置:
import androidx.test.rule.GrantPermissionRule
@RunWith(AndroidJUnit4::class)
open class SomeTest {
@get:Rule
val permissionRule: GrantPermissionRule = GrantPermissionRule.grant(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION)
If you add ACCESS_BACKGROUND_LOCATION
on device where Android < Q or permission that doesn't exist in AndroidManifest you will get an exception .如果您在 Android < Q 或 AndroidManifest 中不存在的权限的设备上添加ACCESS_BACKGROUND_LOCATION
,您将获得异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.