简体   繁体   English

如何在单元测试中注入协程调度程序 - 使用 Koin

[英]How to inject coroutine dispatcher in Unit Test - using Koin

I am injecting my dispatcher, using Koin, into my classes我正在使用 Koin 将调度程序注入我的课程

Extract of one class using Koin使用 Koin 提取一类

class LogsWorker(
    val context: Context,
    workerParameters: WorkerParameters
) : CoroutineWorker(context, workerParameters), KoinComponent {


    private val ioDispatcher: CoroutineDispatcher by inject()
}

koinModule: koin模块:

val appModule = module {
    factory { provideIoDispatcher() }
}

private fun provideIoDispatcher(): CoroutineDispatcher = Dispatchers.IO

If I want to unit test my LogsWorker class, I need to inject a coroutineTestDispatcher.如果我想对我的 LogsWorker 类进行单元测试,我需要注入一个 coroutineTestDispatcher。 How could I do that?我怎么能那样做? I don't find any example anywhere.我在任何地方都找不到任何例子。

You need to override that bean definition in your testing, when you are loading you are starting koin and loading the modules.您需要在测试中覆盖该 bean 定义,当您加载时,您正在启动 koin 并加载模块。

You can do that with: factory(override = true) { provideYourTestingDispatcher }你可以这样做: factory(override = true) { provideYourTestingDispatcher }

Read more about it here 在此处阅读更多相关信息

Although the above could work, I just find it more elegant to use constructor injection instead, for ex:尽管上述方法可行,但我发现使用构造函数注入更优雅,例如:

class LogsWorker(
    val context: Context,
    workerParameters: WorkerParameters,
    private val ioDispatcher: CoroutineDispatcher
) : CoroutineWorker(context, workerParameters)

Then you can just specify the definition for LogsWorker in koin, such as:然后你可以在koin中指定LogsWorker的定义,例如:

factory { (context: Context, workerParameters: WorkerParameters) -> LogsWorker(context, workerParameters, get()) }

And in testing, you can just simply pass in the testing dispatcher.在测试中,您只需传入测试调度程序即可。 More info about this: https://insert-koin.io/docs/reference/koin-core/injection-parameters#defining-an-injected-parameter更多信息: https : //insert-koin.io/docs/reference/koin-core/injection-parameters#defining-an-injected-parameter

UPDATE: override is deprecated, you could use KoinApplication.allowOverride(true) instead更新:不推荐使用override ,您可以使用KoinApplication.allowOverride(true)代替

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM