Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

startKoin in KoinTest-class throws "A KoinContext is already started"

Tags:

kotlin

koin

ktor

I'm using "withTestAppliction" in one of my tests to test if the route works. Before all Tests the DB-Table "cats" should have no entries. To get the DAO I need Koin in this Test but if conflicts with "withTestAppliction" where Koin will also be startet and throws A KoinContext is already started

[Update]
I know I could use something like handleRequest(HttpMethod.Delete, "/cats") but I don't want to expose this Rest-Interface. Not even for testing.

@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())
    }
}

like image 824
Mike Mitterer Avatar asked Apr 14 '20 09:04

Mike Mitterer


1 Answers

After test (after withTestApplication()) call KoinContextHandler.get().stopKoin().

Example: https://github.com/comm1x/ktor-boot/blob/master/test/common/common.kt

like image 59
Pavel Shorokhov Avatar answered Oct 02 '22 08:10

Pavel Shorokhov