Search code examples
androidfiledirectorymockingandroid-contentprovider

getMockContext().getFilesDir()="/dev/null" causing error in test case


I have a method in a ContentProvider which save files to getFilesDir() base path.

However, in tests: getMockContext().getFilesDir()="/dev/null" which causes error because /dev/null is not a directory (files can't be save under that junk-path I suppose).

Can I mock getFilesDir() to some other path on disk?


Solution

  • You can use a TemporaryFolder to generate a temp folder on your system just for the lifecycle of your test (it'll automatically be deleted after your tests end).

    Here's a sample using Mockito to generate mocks.

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