Skip to content

Instantly share code, notes, and snippets.

@roughike
Created February 8, 2017 17:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roughike/0ed405977bcb32acc2a82e57623add53 to your computer and use it in GitHub Desktop.
Save roughike/0ed405977bcb32acc2a82e57623add53 to your computer and use it in GitHub Desktop.
package com.example.myawesomeapp
import io.realm.Realm
import io.realm.RealmConfiguration
import org.junit.rules.ExternalResource
import org.junit.runner.Description
import org.junit.runners.model.Statement
/**
* A JUnit Rule that sets up a test Realm database before each test,
* clears all data from it, and deletes the whole database file alltogether
* after the test completes.
*
* Usage:
*
* @Rule @JvmField
* val realmRule: RealmTestRule = RealmTestRule()
*
* The above assumes that your application logic that uses Realm always uses
* the default instance. Meaning that your code calls Realm.getDefaultInstance()
* and uses that for all database logic.
*/
class RealmTestRule : ExternalResource() {
val testConfig: RealmConfiguration = RealmConfiguration.Builder()
.name("test.realm")
.build()
override fun before() {
Realm.setDefaultConfiguration(testConfig)
with (Realm.getDefaultInstance()) {
executeTransaction(Realm::deleteAll)
close()
}
}
override fun apply(base: Statement?, description: Description?): Statement {
return super.apply(base, description)
}
override fun after() {
Realm.deleteRealm(testConfig)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment