Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 845
JoVer M Avatar asked May 20 '26 10:05

JoVer M


1 Answers

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

}
like image 165
Strauss Avatar answered May 23 '26 13:05

Strauss