问题
Part of my application involves saving a png file to my local files directory, and then shared via a content provider.
I write the file via getContext().openFileOutput
However, in my content provider, ParcelFileDescriptor
will only open actual File objects. So trying to do this via a mocked out content provider using ProviderTestCase2
, the following code doesn't work:
return ParcelFileDescriptor.open(new File(getContext().getFilesDir(), filename), ParcelFileDescriptor.MODE_READ_ONLY)
This is because context.getFilesDir()
points to /dev/null
in the mock context given to the provider via the ProviderTestCase2
code. The code above results in an exception because /dev/null
doesn't count as a directory. Is this as intended?
回答1:
This feels like a joke... The docs say:
Returns the absolute path to the directory on the filesystem where files created with openFileOutput(String, int) are stored.
But the IsolatedContext source is this:
@Override
public File getFilesDir() {
return new File("/dev/null");
}
So we have better ignoring that method and try with
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
in out tests.
来源:https://stackoverflow.com/questions/13796529/android-provider-test-case-2-and-getfilesdir