Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't run unit tests with RobolectricTestRunner and Koin

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?

like image 397
Joks Avatar asked Nov 07 '22 14:11

Joks


1 Answers

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
    }
}

like image 187
Paul Spiesberger Avatar answered Nov 10 '22 00:11

Paul Spiesberger