Kotest Koin Extension

This page introduces the Kotest Koin extension.

The Koin DI Framework can be used with Kotest through the KoinExtension extension.

To use the extension in your project, add the dependency to your project:

io.kotest.extensions:kotest-extensions-koin:${version}

Once the dependency is added, you can use Koin in tests easily.

class KotestAndKoin : FunSpec(), KoinTest {

    override fun extensions() = listOf(KoinExtension(myKoinModule))

    val userService by inject<UserService>()

    init {
        test("use userService") {
            userService.getUser().username shouldBe "LeoColman"
        }
    }
}

By default, the extension starts and stops the Koin context between leaf tests. If you use a nested spec style such as DescribeSpec and want to keep the Koin context across all leaves of a root test, for example to share mock declarations between tests, you can specify the lifecycle mode as KoinLifecycleMode.Root in the KoinExtension constructor.

class KotestAndKoin : DescribeSpec(), KoinTest {

    override fun extensions() = listOf(KoinExtension(module = myKoinModule, mode = KoinLifecycleMode.Root))

    val userService by inject<UserService>()

    init {
        describe("use userService") {
            it("inside a leaf test") {
                userService.getUser().username shouldBe "LeoColman"
            }
            it("this shares the same context") {
                userService.getUser().username shouldBe "LeoColman"
            }
        }
    }
}

References