【问题标题】:Mock Environment.getExternalStorageDirectory() in Android Unit Test在 Android 单元测试中模拟 Environment.getExternalStorageDirectory()
【发布时间】:2019-10-07 13:03:52
【问题描述】:

我想模拟 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)

附:我需要在不使用模拟器或设备的情况下对文件的复制/删除进行单元测试,所以我使用的是Robolectric

【问题讨论】:

    标签: android unit-testing mockito robolectric


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-30
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      • 2017-02-09
      • 2018-11-27
      • 1970-01-01
      相关资源
      最近更新 更多