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.

有帮助吗?

解决方案

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

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top