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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With