【问题标题】:getMockContext().getFilesDir()="/dev/null" causing error in test casegetMockContext().getFilesDir()="/dev/null" 导致测试用例出错
【发布时间】:2016-04-29 14:27:14
【问题描述】:

我在 ContentProvider 中有一个方法可以将文件保存到 getFilesDir() 基本路径。

但是,在测试中: getMockContext().getFilesDir()="/dev/null" 这会导致错误,因为 /dev/null 不是目录(我想文件无法保存在该垃圾路径下)。

我可以将 getFilesDir() 模拟到磁盘上的其他路径吗?

【问题讨论】:

    标签: android file directory mocking android-contentprovider


    【解决方案1】:

    您可以使用TemporaryFolder 在您的系统上生成一个临时文件夹,仅用于您的测试生命周期(测试结束后它会自动被删除)。

    这是一个使用 Mockito 生成模拟的示例。

    import org.junit.Before;
    import org.junit.rules.TemporaryFolder;
    import org.junit.Rule;
    import static org.mockito.MockitoAnnotations.initMocks;
    
    public class SampleTest {
        @Rule public TemporaryFolder mTempFolder = new TemporaryFolder();
    
        @Mock private Context mMockContext;
    
        @Before
        public void setUp() throws IOException {
            initMocks(this);
            when(mMockContext.getFilesDir()).thenReturn(mTempFolder.newFolder());
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      相关资源
      最近更新 更多