Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to grant permissions to android instrumented tests?

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 

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?

like image 998
JavaBanana Avatar asked May 18 '18 02:05

JavaBanana


People also ask

What is an instrumented test Android?

Instrumented tests run on Android devices, whether physical or emulated. As such, they can take advantage of the Android framework APIs. Instrumented tests therefore provide more fidelity than local tests, though they run much more slowly.

How do I check if permission is granted Android?

To check if the user has already granted your app a particular permission, pass that permission into the ContextCompat. checkSelfPermission() method. This method returns either PERMISSION_GRANTED or PERMISSION_DENIED , depending on whether your app has the permission.

Why do you use the AndroidJUnitRunner when running UI tests?

When you use AndroidJUnitRunner to run your tests, you can access the context for the app under test by calling the static ApplicationProvider. getApplicationContext() method. If you've created a custom subclass of Application in your app, this method returns your custom subclass's context.


2 Answers

Use GrantPermissionRule. Here's how:

Add the following dependency to app/build.gradle:

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

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);     ... } 
like image 124
donturner Avatar answered Nov 08 '22 17:11

donturner


You can grant the permission as follows:

@RunWith(AndroidJUnit4.class) public class MyInstrumentationTest {     @Rule     public GrantPermissionRule permissionRule = GrantPermissionRule.grant(Manifest.permission.READ_SMS);     ...  } 
like image 42
Sagar Avatar answered Nov 08 '22 16:11

Sagar