Trying to mock Environment.getExternalStorageState

android, environment, mocking, mockito, unit-testing

Solution

You could write helper around this call and easily mock it after (sorry for having helper part in class name):

public class EnvironmentHelper {
    public String getStorageState() {
        return Environment.getExternalStorateState();
    }     
}

Or if you use Robolectric you could call:

ShadowEnvironment.setExternalStorageState(Environment.MEDIA_MOUNTED);

It depends on your setup and needs but I would recommend to invest in Robolectric usage

Problem

I've been trying to figure out for some hours how to mock the call to `Environment.getExternalStorateState()` while unit testing my Android App. I've been able to mock SystemServices, Providers and Services, but I cannot work out how to mock this call, as it is not a call to something provided within my context, but something in the OS environment. Would be grateful about some help.

Original source