lundi 24 avril 2017

Android ContentProvider test with file access

I have a ContentProvider that accesses files from Context.getFilesDir() via a helper class StorageHelper that creates the necessary directory in its constructor:

StorageHelper(Context ctx) throws FileNotFoundException {
    // Set up directories and makes sure the final directory exists
    eventsDir = new File(ctx.getFilesDir(), SUBDIR);
    if(!eventsDir.exists()) {
        eventsDir.mkdirs();
    }
}

In my ContentProvider's onCreate(), an instance of this helper is created with the Context of the ContentProvider:

public boolean onCreate() {
    Context context = getContext();

    // Set up file helper
    try {
        fileHelper = new LESStorageHelper(context);
    }
    catch(FileNotFoundException e) {
        Log.e(getClass().getSimpleName(), "Unable to create content provider " + e.toString());
        return false;
    }

    return true;
}

I have set up an instrumented test case that will test my ContentProvider, but the call to Context.getFilesDir() returns /dev/null, which seems to be due to the context of the ContentProvider. I mock the Context.getFilesDir() in my test class, which allows me to check the status of the files that should be created, but I haven't been able to get the ContentProvider and thus its StorageHelper to be set up with that same context. I have tried setContext(), but that doesn't seem to work.

@Mock private Context context;
@Rule public TemporaryFolder testFilesDir = new TemporaryFolder();
private StorageHelper storageHelper;

@Before
@Override
public void setUp() throws Exception {
    super.setUp();

    initMocks(this);

    when(context.getFilesDir()).thenReturn(testFilesDir.newFolder());
    setContext(context);

    storageHelper = new StorageHelper(context);
}

Is there a way for me to pass the context to my ContentProvider or intercept the call to getFilesDir() so that it works consistently through both normal use and in a testing environment? Is there something that I may have missed here? I haven't been able to find any documentation about testing a ContentProvider that uses files instead of sqlite.

Aucun commentaire:

Enregistrer un commentaire