5

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?

Joks
  • 309
  • 2
  • 17
  • Why does your test class extend a class that extends KoinComponent? – Ricardo Aug 06 '19 at 10:45
  • @Ricardo You misunderstood me, I have another class(BroadcastReceiver) that extends KoinComponent not test class – Joks Aug 06 '19 at 13:46

1 Answers1

1

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

Paul Spiesberger
  • 5,630
  • 1
  • 43
  • 53