首页 > 解决方案 > 如何使用 Koin 测试 Ktor 模块?

问题描述

我有一个安装了 Koin 的模块。我需要模拟一些注入的依赖项来执行测试。我在任何地方都找不到如何正确地做到这一点。你能告诉我怎么做吗?

class AudioFilesHandlerTest : DescribeSpec(), KoinTest {

private val deviceAuthService by inject<DeviceAuthenticationService>() // it should provide mocked object

    init {
        describe("AudioFilesHandler") {
            val audioFilesUri = "/api/audio-files"

            describe(audioFilesUri) {
                describe("when device is registered") {
                    val product = createProduct() // Factory for tests
                    val device = createDevice(product = product)
                    every { deviceAuthService.challenge(product.productId, device.deviceId) } returns device // this line doesn't work

                    describe("and transcription or audio params are missing") {
                        it("should returns 400") {
                            withApplication(testEnv) {
                                val call = handleRequest(uri = audioFilesUri, method = HttpMethod.Post) {
                                    val boundary = "WebAppBoundary"
                                    addHeader(ContentType, FormData.withParameter("boundary", boundary).toString())
                                    addHeader("productId", product.productId)
                                    addHeader("deviceId", device.deviceId)
                                }

                                call.response.status() shouldBe HttpStatusCode.Unauthorized
                            }
                        }
                    }
                }
            }
        }
    }
}

标签: kotlinktorkoin

解决方案


推荐阅读