我想模拟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.setExternalStorageState(filesDir, Environment.MEDIA_MOUNTED)
P.S。我需要在不使用模拟器或设备的情况下对文件的复制/删除进行单元测试,所以我正在使用Robolectric
。
答案 0 :(得分:0)
您可以尝试为此使用临时文件夹。
@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());
}
}