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

问题描述 投票:4回答:1

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

android unit-testing robolectric koin
1个回答
0
投票

As you can read here,在AndroidManifest中声明的BroadcastReceivers在应用程序的onCreate之前创建。因此,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
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.