Testing in Android can be complex, especially when your component is not isolated from the Android framework. One example of this is when your component is performing file system tasks using Context. E.g, the Activity class has the following methods (inherited from Context):
When calling any of the methods above, Context directs the calls to parts of the file system dedicated to your specific application, usually located under
/data/data/<your.applications.package.name>/. To mock away these type of operations, there is a component called RenamingDelegatingContext. It basically allows you to replace the context used when calling file system methods, re-directing the call to a mocked data file instead of the real file. The source code for RenamingDelegatingContext can be looked at here:
There are a number of tutorials on how to use RenamingDelegatingContext to mock away your files or databases;
Uri uri = Uri.parse("content://authority/path");
InputStream is = getContext().getContentResolver().openInputStream(uri);
getContext() call can be omitted if you’re making the call from within an Activity or Service, where the component itself is a Context.
One might want the returned InputStream to point to a test resource instead of the real resource. This can be achieved with some research. When opening the InputStream, the ContentResolver finds the proper provider for the given authority (see ContentProvider section for more detail). The source code reveals more on how this is done: