I have an application for Android where I use Realm to persist data. I now want to write a unit test for this application, utilizing Realm.
However, I do not want the unit test to interfere with my existing Realm data. So I want to generate different Realm files for my test Instance. I don't care if they have a different name, or are stored in a different directory.
I have tried to use a RenamingDelegatingContext
, but with no success. According to https://groups.google.com/forum/#!msg/realm-java/WyHJHLOqK2c/WJFYvglIGk0J getInstance()
only uses the Context
to call getFilesDir()
, which does not seem to be overwriting the getFilesDir()
method, so I end up using my live data for testing.
Next I tried to use IsolatedContext
, but IsolatedContext.getFilesDir()
returns null
, so this also was not successful.
Finally, I tried to write a class extending RenamingDelegatingContext
, overwriting getFilesDir()
, return a different directory for Realm to use. I created the directory using the DeviceMonitor of AndroidStudio, but when I try to use this context, Realm fails with an io.realm.exceptions.RealmIOException: Failed to open . Permission denied. open() failed: Permission denied
.
Does anyone know if there is a possibility to test Realm without affecting live data?
I was actually quite blind, with the solution being quite easy by just using a different name for the RealmDatabase during test setup while generating its configuration. My solution now looks as follows:
RealmConfiguration config = new RealmConfiguration.Builder(getContext()).
schemaVersion(1).
migration(new CustomMigration()).
name("test.realm").
inMemory().
build();
Realm.setDefaultConfiguration(config);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With