0
1

[Android] Hiltを使ったテスト中のデータベース差し替え方法

Posted at

はじめに

ComposeのUIテストを行う際に、DBをin memoryに差し替えたいなと思って調べた結果を簡潔にまとめました!

Custom test runnerの設定

HiltでのDB差し替えをテストで使うには専用のHiltTestApplicationを使う必要がある。なのでCustomTestRunnerを設定、gradleでそれを使うように指定する。

class CustomTestRunner : AndroidJUnitRunner() {
    override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
        // HiltTestApplicationをテスト用のApplicationクラスとして使用
        return super.newApplication(cl, HiltTestApplication::class.java.name, context)
    }
}
// build.gradle
defaultConfig {
    testInstrumentationRunner "com.example.myapp.CustomTestRunner"
}

対象のテストでModuleを差し替える

以下のDB用Moduleがあるとする。

@Module
@InstallIn(SingletonComponent::class)
object DatabaseModule {
    @Provides
    @Singleton
    fun provideDatabase(application: Application): KaimonoDatabase {
        return Room.databaseBuilder(application, MyDatabase::class.java, "kaimono_database")
            .fallbackToDestructiveMigration()
            .build()
    }
}

これを差し替えたいUIテストなどで以下のように設定するとHiltによるDB入れ替えを行える。やっていることとしては、@UninstallModulesで既存Moduleをuninstall, @InstallInで再度テスト用moduleをinstall。

@HiltAndroidTest
@UninstallModules(DatabaseModule::class)
class RegisterItemTest {
    @get:Rule
    val composeTestRule = createAndroidComposeRule<MainActivity>()
    @get:Rule
    var hiltRule = HiltAndroidRule(this)
    // use createAndroidComposeRule<YourActivity>() if you need access to an activity

    // テスト用のDBモジュールを作成
    @Module
    @InstallIn(SingletonComponent::class)
    object TestDatabaseModule {
        @Provides
        @Singleton
        fun provideInMemoryDb(@ApplicationContext context: Context): KaimonoDatabase {
            return Room.inMemoryDatabaseBuilder(context, MyDatabase::class.java)
                .allowMainThreadQueries()
                .build()
        }
    }

    @Test
    fun myTest() {
			...
    }
}

おわり

以上です!
何かコメントやもっとこうやったほうがいいなどあれば是非お願いします!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1