Hi :slightly_smiling_face: has anyone experience t...
# kodein
c
Hi 🙂 has anyone experience testing a ktor app using the kodein DI Feature? I've got an application that looks like this:
Copy code
fun Application.main() {
    di {
        bind<SomeService>() with singleton { SomeService(environment.config) }
    }
...
I use the service somewhere in the app, in the routes, etc. My tests (kotest) look like that:
Copy code
"A Request should do something" {
    withServer {
        val req = handleRequest {
            uri = "/someroute"
        }

        req.requestHandled shouldBe true
        req.response shouldHaveStatus HttpStatusCode.OK
    }
}
withServer
is a wrapper for
withTestApplication({ main() }, test)withTestApplication({ main() }, block)
My problem is that I currently need to test against a real database as I don't get the DI mock to work. Any hints for me here? Thanks!
r
Hi, maybe you could declare your bindings in a container, then pass it to your application, mocking it should be easy after that
Copy code
val appDI = DI {
    bind<SomeService>() with singleton { SomeService(environment.config) }
}

fun Application.run(di: DI) {
    di {
        extend(appDI)
    }
}

fun Application.main() {
    run(appDI)
}
and in your tests something like
Copy code
val mockDI = DI { 
        bind<SomeService>() with singleton { SomeMockService() }
    }
    withTestApplication({ run(mockDI) }, test)
🙌 1
c
Thank you very much, it works 🙂 I tried a similar solution before, but I've overridden the main() function instead of creating an alternative like run(), so it always used the one without parameters 😅