Android: Provider Test Case 2 and getFilesDir()

大兔子大兔子 提交于 2019-12-23 20:51:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!