I am using InstrumentationTestCase to unit test a component of my application.
The component persists data to the internal storage and uses Context::fileList(); to retrieve the persisted files.
I experience the following problem: Using this method in the app (on the device) works perfectly fine. But when I try to (Android-)Unit-Test (also on the Device) with use of InstrumentationTestCase I get a NullPointerException inside the fileList() method. I digged into the android source and found out that getFilesDir() (see source here) returns null and causes this error.
The code to reproduce is the following:
public class MyTestCase extends InstrumentationTestCase
{
public void testExample() throws Exception
{
assertNotNull(getInstrumentation().getContext().getFilesDir()); // Fails
}
}
My questions are: Is this behaviour intended? What can I do to circumvent this issue? Am I using InstrumentationTestCase right or should I use something different?
I found this question but I’m not sure if this covers the same problem I have.
I think that you are right with keeping your test data separate from tested application.
You can fix problem with
Nullby creatingfilesdirectory forInstrumentationapp by executing the following commandsYou can do above only on emulator or rooted device.
Then test from your question will not fail. I did it and also uploaded file named
tst.txttofilesdir, all below tests were successful:But I think more convenient way to provide data to test project is to use
assetsof test project where you can simply save some files and open them:or if you want to save some results of tests to the file you can use
ExternalStorage: