无法使用RobolectricTestRunner和Koin运行单元测试

时间:2019-08-06 10:02:07

标签: android unit-testing robolectric koin

我有一个带有RobolectricTestRunner的测试类,用于获取应用程序上下文,并且我还扩展了一个带有KoinComponent的类。当我开始测试时,它返回java.lang.IllegalStateException: KoinApplication has not been started并指向扩展KoinComponent的类。我尝试使用加载模块的setUp()方法启动Koin并删除了Robolectric,但这种方式无法找到应用程序上下文。有没有办法用Robolectric和Koin编写单元测试?

1 个答案:

答案 0 :(得分:0)

在应用程序的BroadcastReceivers之前创建在AndroidManifest中声明的

As you can read hereonCreate。因此,Koin尚未初始化。一种解决方法是为您的广播接收器创建一个助手,并懒惰地初始化该助手:

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