KoinTest 类中的 startKoin 抛出“A KoinContext 已经启动”

Mik*_*rer 7 kotlin ktor koin

我在我的一项测试中使用“withTestAppliction”来测试路由是否有效。在所有测试之前,DB-Table“cats”应该没有条目。为了获得 DAO,我需要在此测试中使用 Koin,但如果与“withTestAppliction”冲突,Koin 也将启动并抛出A KoinContext is already started

[更新]
我知道我可以使用类似的东西,handleRequest(HttpMethod.Delete, "/cats")但我不想公开这个 Rest-Interface。甚至不是为了测试。

@ExperimentalCoroutinesApi
class CatsTest: KoinTest {
    companion object {
        @BeforeClass
        @JvmStatic fun setup() {
            // once per run
            startKoin {
                modules(appModule)
            }
        }

        @AfterClass
        @JvmStatic fun teardown() {
            // clean up after this class, leave nothing dirty behind
            stopKoin()
        }
    }

    @Before
    fun setupTest() = runBlockingTest {
        val dao = inject<CatDAO>()
        dao.value.deleteAll()
    }

    @After
    fun cleanUp() {

    }

    @Test
    fun testCreateCat() {
        withTestApplication({ module(testing = true) }) {
            val call = createCat(predictName("Pepples"), 22)

            call.response.status().`should be`(HttpStatusCode.Created)
        }
    }

}

fun TestApplicationEngine.createCat(name: String, age: Int): TestApplicationCall {
    return handleRequest(HttpMethod.Post, "/cats") {
        addHeader(HttpHeaders.ContentType, ContentType.Application.FormUrlEncoded.toString())
        setBody(listOf(
                "name" to name,
                "age" to age.toString()
        ).formUrlEncode())
    }
}

Run Code Online (Sandbox Code Playgroud)

Sah*_*bra 0

它看起来与我面临的问题相似。问题在于,module()在 下传递的对象withTestApplication()正在尝试再次创建该Koin对象。我module()用除 Koin 之外的测试必须加载的特定模块替换了 。

参考-测试样本应用样本