Question

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.

Was it helpful?

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

OTHER TIPS

I just worked around wrapping the call to the Environment method in my test helper class so I could mock the status of the SD Card as I wanted depending on a variable I could set as desired in each test case. Best solution I think.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top