Home » Android » java – Testing Realm under Android

java – Testing Realm under Android

Posted by: admin June 15, 2020 Leave a comment

Questions:

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?

How to&Answers:

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);

Answer:

If you are using JUnit4 you can use the TemporaryFolder rule to generate a test folder: https://garygregory.wordpress.com/2010/01/20/junit-tip-use-rules-to-manage-temporary-files-and-folders/

@Rule
public TemporaryFolder testFolder = new TemporaryFolder();

@Test
public void testRealm() throws IOException {
    File tempFolder = testFolder.newFolder("realmdata");
    RealmConfiguration config = new RealmConfiguration.Builder(tempFolder).build();

    Realm realm = Realm.getInstance(config);
    // Do test
    realm.close(); // Important
}

Answer:

A minor alternative to using setDefaultConfiguration might be to directly use Realm.getInstance in @BeforeClass:

RealmConfiguration testConfig = 
   new RealmConfiguration.Builder().
      inMemory().
      name("test-realm").build();

Realm testRealm = Realm.getInstance(testConfig);

and inject the testRealm into your classes.