koin-test

Testing with Koin

Easy and straight forward features to test your app with Koin.

Setup

First, check that the koin-test dependency is added like below:

// Add Jcenter to your repositories if needed
repositories {
    jcenter()    
}
dependencies {
    
    testImplementation 'org.koin:koin-test:1.0.2'
}

Bring Koin powers to your test class

Just tag your test class with KoinTest, and you will be able to unlock features:

  • by inject() - lazy inject an instance
  • get() - retrieve an instance
  • declareMock() - declare a mock (mockito) for given type
  • declare { } - declare a definition on the fly

Given classes and module:

class ComponentA
class ComponentB(val a: ComponentA)

val appModule = module {
        single { ComponentA() }
        single { ComponentB(get()) }
    }

We can write the test below:

class MyTest : KoinTest {

    // Lazy inject property
    val componentB : ComponentB by inject()

    @Test
    fun `should inject my components`() {
        startKoin(listOf(appModule)))

        // directly request an instance
        val componentA = get<ComponentA>()

        assertNotNull(a)
        assertEquals(componentA, componentB.a)
    }
}

Note that you can use the standard startKoin() function to start Koin from your test. Don’t forget to close it between tests.

Checking your modules

You can check if your modules are good (all definitions are bounded):

    @Test
    fun `check module`() {
        checkModules(listOf(appModule)))
    }

More about testing with Koin