DatabaseRule.kt
TLDR
This file contains the DatabaseRule
class, which is a JUnit rule for managing a database in Android instrumented tests. It provides methods for creating and deleting a database before and after the test execution.
Classes
DatabaseRule
The DatabaseRule
class is a JUnit rule that manages a database for Android instrumented tests. It provides the following functionality:
apply(base: Statement, description: Description): Statement
This method is overridden from the TestRule
interface and applies the database rule to a test method. It creates a new Statement
object that wraps the base statement, which represents the test method invocation. Within this new statement, the following operations are performed:
- Retrieve the instrumentation and target context.
- Delete the database (if it exists) using the
LeaksDbHelper.DATABASE_NAME
constant. - Create a new instance of
ScopedLeaksDb
with a writable database. - Invoke the base statement's
evaluate()
method to run the test method. - Delete the database again to clean up.
By using this rule, the database is created and deleted automatically before and after each test execution.
package leakcanary
import android.database.sqlite.SQLiteDatabase
import androidx.test.platform.app.InstrumentationRegistry
import leakcanary.internal.activity.db.LeaksDbHelper
import leakcanary.internal.activity.db.ScopedLeaksDb
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
class DatabaseRule(private val updateDb: (SQLiteDatabase) -> Unit = {}) : TestRule {
override fun apply(
base: Statement,
description: Description
): Statement {
return object : Statement() {
override fun evaluate() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
val context = instrumentation.targetContext
context.deleteDatabase(LeaksDbHelper.DATABASE_NAME)
ScopedLeaksDb.writableDatabase(context, updateDb)
base.evaluate()
context.deleteDatabase(LeaksDbHelper.DATABASE_NAME)
}
}
}
}