JohnyTex JohnyTex - 1 year ago 74
Android Question

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:
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?

Answer Source

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;

    public void setUp() throws IOException {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download