Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock permissions for testing in Android?

With Android 6.0 and new permission model, I am checking if the permission exists before performing certain task.

I want to assign these permissions to available and not available for testing purpose. I have a static class to check various permissions depending on the string.

boolean result = ContextCompat.checkSelfPermission(context, name) == PackageManager.PERMISSION_GRANTED;

Can it be achieved using Mockito or Roboelectric?

like image 417
sat Avatar asked Oct 02 '15 09:10

sat


1 Answers

If you move your permission checker to a collaborator class, you can mock the collaborator. I am not familiar with the Android return types but the solution would look like this:

class PermissionsChecker {
    public String checkSelfPermission(context, name) {
       return ContextCompat.checkSelfPermission(context, name);
    }
}
class YourApp {
    private PermissionsChecker permissionsChecker; //need to inject this via setter or constructor
    public doSomething() {
       boolean result = permissionsChecker.checkSelfPermission(context, name).equals(PackageManager.PERMISSION_GRANTED);
    }
}
class YourAppTest {
   PermissionsChecker permissionsChecker = mock(PermissionsChecker.class);
   @InjectMocks YourApp app = new YourApp();
   @Test
   public void hasPermissions() {
      when(permissionsChecker.checkSelfPermission(...)).thenReturn("NOT GRANTED");
      app.something();
      //verify you get some error
    }
}
like image 66
Andrew R. Freed Avatar answered Oct 23 '22 04:10

Andrew R. Freed