我有一个带有RobolectricTestRunner
的测试类,用于获取应用程序上下文,并且我还扩展了一个带有KoinComponent
的类。当我开始测试时,它返回java.lang.IllegalStateException: KoinApplication has not been started
并指向扩展KoinComponent
的类。我尝试使用加载模块的setUp()
方法启动Koin并删除了Robolectric,但这种方式无法找到应用程序上下文。有没有办法用Robolectric和Koin编写单元测试?
答案 0 :(得分:0)
BroadcastReceivers
之前创建在AndroidManifest中声明的 As you can read here,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
}
}