Hello, are there any up to date examples of testin...
# ktor
k
Hello, are there any up to date examples of testing a ktor app that uses koin for DI?
f
I am using Koin in my unit testing, is there anything in particular you need to know?
k
I've been using this as an example https://github.com/thomasneuteboom/ktor-koin-example/blob/master/src/test/kotlin/koinexample/ApplicationTest.kt. So I am using
loadKoinModules
in my test to add the test implementation to be injected instead but I get
KoinApplication has not been started
in my Application module I have
Copy code
install(Koin)  {
    modules(appModule)
}
Copy code
val appModule = module {
    single { DateProvider { org.joda.time.LocalDate.now() } }
}
f
If you are initializing Koin within you server module, you need to define the test method as follows:
Copy code
@Test
fun yourTest() = testApplication {
    // Start the application so that the Koin DI container is initialized.
    startApplication()
.....
}
See this test in my pet project: https://github.com/perracodex/Kcrud/blob/master/kcrud-server/src/test/kotlin/BackPressureTest.kt If instead, you are testing a functionality that does not start your server module, then you need to start Koin manually in the actual unit test with the modules you wish to inject. See next: https://github.com/perracodex/Kcrud/blob/master/kcrud-base/src/test/kotlin/RbacServiceTest.kt You will see a call to
TestUtils.setupKoin()
in the unit test
setUp()
method, which is configured to run before each test. For my particular test:
Copy code
fun setupKoin(modules: List<Module> = emptyList()) {
    val baseModules: List<Module> = listOf(
        RbacInjection.get(),
        ActorInjection.get()
    )

    startKoin {
        modules(baseModules + modules)
    }
}
See also: https://github.com/perracodex/Kcrud/blob/master/kcrud-base/src/main/kotlin/kcrud/base/infrastructure/utils/TestUtils.kt The key is to call next whenever you start a test, where
modules
is the actual list of Koin modules to make available to the test.
Copy code
startKoin {
    modules(modules)
}
And do not forget to stop Koin on the test
tearDown
Let me know if you need more clarification.
k
thank you very much, I'll give it a go!