I want to write test for koin
. I use RoomDatabase
, which receives context in constructor. App works well but test fails
Can't resolve Application instance. Please use androidContext() function in your KoinApplication configuration.
if you want context in your modules, you should pass context in your start koin method
// start Koin!
startKoin {
// declare used Android context
androidContext(this@MyApplication)
// declare modules
modules(yourModule)
}
and use these libraries
// Koin AndroidX Scope features
implementation "org.koin:koin-android-scope:2.0.1"
// Koin AndroidX ViewModel features
implementation 'org.koin:koin-androidx-viewmodel:2.0.1'
// Koin AndroidX Experimental features
implementation "org.koin:koin-android-ext:2.0.1"
Make sure to set your context when you start koin. Then you should be able to access it via androidContext() in your modules.
startKoin {
androidContext(this@App)
modules(...)
...
}
For unittests I have implemented this
@file:JvmName("KoinTest")
package com.myapp.di
import androidx.test.core.app.ApplicationProvider
import org.koin.android.ext.koin.androidContext
import org.koin.core.context.startKoin
fun startKoin() {
startKoin {
androidContext(ApplicationProvider.getApplicationContext())
modules(listOf(applicationModule, networkModule))
}
}
fun stopKoin() {
org.koin.core.context.stopKoin()
}
I can call this from our old Java tests as KoinTest.startKoin()
or just startKoin()
in Kotlin. I call these from the @Before
and @After
block appropriately. The android context is set with the new AndroidX test library function.
You cannot test Room in unit testing with Koin. You can only test in instrumented tests.
in my case, I edit my application class to :
class App : Application() {
override fun onCreate() {
super.onCreate()
startKoin {
androidContext(this@App)
modules(viewModelModule)
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.