I have a test class with RobolectricTestRunner which I use for getting application context and also I extend one class with KoinComponent. When I started my test it returned java.lang.IllegalStateException: KoinApplication has not been started and points to my class that extends KoinComponent. I tried to start Koin in setUp() method with loading modules and removed Robolectric but in this way it can't find application context. Is there a way to write unit test with Robolectric and Koin?
As you can read here, BroadcastReceivers declared in the AndroidManifest get created before your Application's onCreate. Therefore, Koin is not yet initialized. A workaround for that is to create a Helper for your Broadcast Receiver and initialize the Helper lazy:
class MyBroadcastReceiver : BroadcastReceiver() {
// Broadcast Receivers declared in the AndroidManifest get created before your Application's onCreate.
// The lazy initialization ensures that Koin is set up before the broadcast receiver is used
private val koinHelper: BroadcastReceiverHelper
by lazy { BroadcastReceiverHelper() }
override fun onReceive(context: Context, intent: Intent) {
koinHelper.onReceive(context, intent)
}
}
class BroadcastReceiverHelper : KoinComponent {
private val myClassToInject: MyClassToInject by inject()
fun onReceive(context: Context, intent: Intent) {
// do stuff here
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With