JoVer M
JoVer M

Reputation: 180

Mock Environment.getExternalStorageDirectory() in Android Unit Test

I want to mock the Environment.getExternalStorageDirectory() and point it to "C:\Users\\Android-Test\". I tried both of below options but nothing worked:

  1. Mocked the 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);
  1. Used ShadowEnvironment
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.

Upvotes: 3

Views: 1853

Answers (1)

Strauss
Strauss

Reputation: 737

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());
   }

}

Upvotes: 3

Related Questions