【问题标题】:Can't run unit tests with RobolectricTestRunner and Koin无法使用 RobolectricTestRunner 和 Koin 运行单元测试
【发布时间】:2019-08-06 10:02:07
【问题描述】:

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

【问题讨论】:

  • 为什么你的测试类扩展了一个扩展 KoinComponent 的类?
  • @Ricardo 你误会我了,我有另一个类(BroadcastReceiver)扩展了 KoinComponent 而不是测试类

标签: android unit-testing robolectric koin


【解决方案1】:

As you can read hereBroadcastReceivers 在您的应用程序的onCreate 之前创建在 AndroidManifest 中声明。因此,Koin 尚未初始化。一种解决方法是为您的广播接收器创建一个 Helper 并懒惰地初始化 Helper:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 2015-08-20
    • 2018-03-01
    • 2018-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多