尝试使用MigrationTestHelper类和Robolectric测试房间迁移。我们希望将其作为JUnit测试,因为我们的CI环境无法启动仿真器。 (请为模拟器提供CI修复程序,请提供答案,CI不在我的控制范围内。)我唯一遇到的问题是测试失败,因为它找不到架构。我的build.gradle已经包含了它
android {
sourceSets {
test.assets.srcDirs += files("$projectDir/schemas".toString())
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
test {
java.srcDirs += "$projectDir/src/sharedTest/java"
}
testOptions {
unitTests {
includeAndroidResources = true
}
unitTests.all {
systemProperty 'robolectric.enabledSdks', '21'
}
}
}
dependencies {
// has all the proper dependencies from mockito adn robolectric to kotlin and junit.
}
这是测试代码,但是再次调用数据库创建时找不到其大部分模式。 json文件也位于架构目录中
@RunWith(RobolectricTestRunner::class)
class Migration19To20Test {
private val migration = MyDatabase.MIGRATION_19_20
private val fromVersion = 19
private val toVersion = 20
@get:Rule
val helper: MigrationTestHelper = MigrationTestHelper(
InstrumentationRegistry.getInstrumentation(),
MyDatabase::class.java.canonicalName,
FrameworkSQLiteOpenHelperFactory())
private val testDatabaseName = "migration-test"
@Test
fun insertsFirmwareVersionFullColumn() {
givenADatabase()
val validateDroppedTables = true
val db = helper.runMigrationsAndValidate(
testDatabaseName,
toVersion,
validateDroppedTables,
migration)
db.query("select * from ${DatabaseConstants.Table.People}").use { cursor ->
cursor.moveToFirst()
assertTrue("table should contain the ${DatabaseConstants.Column.People.NAME_FULL} column as it should have been added",
cursor.columnNames.contains(DatabaseConstants.Column.People.NAME_FULL))
}
}
private fun givenADatabase() {
// Test fails here
helper.createDatabase(testDatabaseName, fromVersion)
}
}
答案 0 :(得分:0)
我通过将MigrationTestHelper
复制到测试源代码并修改了loadSchema方法使其看起来像这样来解决了
private SchemaBundle loadSchema(Context context, int version) throws IOException {
// InputStream input = context.getAssets().open(mAssetsFolder + "/" + version + ".json");
InputStream input = new FileInputStream("./schemas/" + mAssetsFolder + "/" + version + ".json");
return SchemaBundle.deserialize(input);
}
schemas
目录是在build.gradle中配置的
android {
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
arguments = [
"room.schemaLocation" : "$projectDir/schemas".toString(),
"room.incremental" : "true",
"room.expandProjection": "true"]
}
}
}
}
您可以看到,原因是该类在assets
目录中寻找迁移,因为Google假定您将在设备上运行这些迁移。在这种情况下,您必须将它们包含在android资产中。
使用Robolectric,它只是从目录中读取内容并将其放入流中。