I want to mock the Environment.getExternalStorageDirectory() and point it to "C:\Users\\Android-Test\". I tried both of below options but nothing worked:
RuntimeEnvironment.application thinking that it will also mock the Environment but it didn't.File filesDir = new File(System.getProperty("user.home") + "\\Android-Test\\" + application.getPackageName());
RuntimeEnvironment.application = spy(RuntimeEnvironment.application);
when(RuntimeEnvironment.application.getApplicationContext()).thenReturn(RuntimeEnvironment.application);
when(RuntimeEnvironment.application.getFilesDir()).thenReturn(filesDir);
ShadowEnvironment.setExternalStorageState(filesDir, Environment.MEDIA_MOUNTED)
P.S. I need to unit test copying/deleting of files without the use of emulator or devices, so I'm using Robolectric.
You can try using Temporary Folder for this.
@RunWith(PowerMockRunner.class)
@PrepareForTest(Environment.class)
public class ExternalStorageTest() {
@Rule
TemporaryFolder tempFolder = new TemporaryFolder();
@Before
public void doSetup() {
PowerMockito.mockStatic(Environment.class);
when(Environment.getExternalStorageDirectory()).thenReturn(tempFolder.newFolder());
}
}
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