模拟环境.在Android单元测试中getExternalStoragedirectory()



我想模拟 Environment.getExternalStorageDirectory(),并将其指向" c: users \ android-test " 。我尝试了以下两个选项,但没有任何作用:

  1. 嘲笑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);
  1. 使用的Shadowenvironment
ShadowEnvironment.setExternalStorageState(filesDir, Environment.MEDIA_MOUNTED)

P.S。我需要在不使用仿真器或设备的情况下对文件进行单元测试复制/删除,因此我使用Robolectric

您可以尝试使用临时文件夹。

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

相关内容

  • 没有找到相关文章

最新更新