Testing Realm for Android

I have an Android app where I use Realm to save data. Now I want to write unit test for this application using 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 tried using a RenamingDelegatingContext , but without success. According to https://groups.google.com/forum/#!msg/realm-java/WyHJHLOqK2c/WJFYvglIGk0J getInstance() uses only Context to call getFilesDir() , which does not seem to overwrite getFilesDir() , so I end up As a result, I use my data for testing.

Next, I tried to use IsolatedContext , but IsolatedContext.getFilesDir() returns null , so this also failed.

Finally, I tried to write a class extending RenamingDelegatingContext , overwriting getFilesDir() , returning another directory for use in Realm. I created a directory using DeviceMonitor AndroidStudio, but when I try to use this context, Realm crashes using io.realm.exceptions.RealmIOException: Failed to open . Permission denied. open() failed: Permission denied io.realm.exceptions.RealmIOException: Failed to open . Permission denied. open() failed: Permission denied io.realm.exceptions.RealmIOException: Failed to open . Permission denied. open() failed: Permission denied .

Does anyone know if it is possible to test Realm without affecting the data in real time?

+7
java android unit-testing realm
source share
3 answers

I was actually completely blind, and the solution was quite simple, just using a different name for RealmDatabase while installing the test when creating its configuration. Now my solution is as follows:

 RealmConfiguration config = new RealmConfiguration.Builder(getContext()). schemaVersion(1). migration(new CustomMigration()). name("test.realm"). inMemory(). build(); Realm.setDefaultConfiguration(config); 
+8
source share

If you use JUnit4, you can use the TemporaryFolder rule to create 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 } 
+7
source share

A small alternative to using setDefaultConfiguration can be directly use Realm.getInstance in @BeforeClass :

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

and enter testRealm in your classes .

+1
source share