【发布时间】:2019-10-07 13:03:52
【问题描述】:
我想模拟 Environment.getExternalStorageDirectory() 并将其指向 "C:\Users\\Android-Test\"。我尝试了以下两个选项,但没有任何效果:
- 嘲笑
RuntimeEnvironment.application,以为它也会嘲笑Environment,但事实并非如此。
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
ShadowEnvironment.setExternalStorageState(filesDir, Environment.MEDIA_MOUNTED)
附:我需要在不使用模拟器或设备的情况下对文件的复制/删除进行单元测试,所以我使用的是Robolectric。
【问题讨论】:
标签: android unit-testing mockito robolectric