Getting started with JUnit Tests

Let’s test our Koin injected application

About

This tutorial lets you test a Kotlin application and use Koin inject and retrieve your components.

Get the code

Checkout the project directly on Github or download the zip file

Gradle Setup

First, add the Koin dependency like below:

// Add Jcenter to your repositories if needed
repositories {
    jcenter()
}
dependencies {
    // Koin testing tools
    testcompile 'org.koin:koin-test:1.0.1'
}

Declared dependencies

We reuse the koin-core getting-started project, to use the koin module:

val helloModule = module {
    single { HelloMessageData() }
    single { HelloServiceImpl(get()) as HelloService }
}

Writing our first Test

To make our first test, let’s write a simple Junit test file and extend it with KoinTest. We will be able then, to use by inject() operators.

class HelloAppTest : KoinTest() {

    val model by inject<HelloMessageData>()
    val service by inject<HelloService>()

    @Before
    fun before() {
        startKoin(listOf(helloModule))
    }

    @After
    fun after() {
        closeKoin()
    }

    @Test
    fun tesKoinComponents() {
        val helloApp = HelloApplication()
        helloApp.sayHello()

        assertEquals(service, helloApp.helloService)
        assertEquals("Hey, ${model.message}", service.hello())
    }
}

You can even make Mocks directly into MyPresenter, or test MyRepository. Those components doesn’t have any link with Koin API.

class HelloMockTest : AutoCloseKoinTest() {

    val service: HelloService by inject()

    @Before
    fun before() {
        startKoin(listOf())
        declareMock<HelloService>()
    }

    @Test
    fun tesKoinComponents() {
        HelloApplication().sayHello()

        Mockito.verify(service).hello()
    }
}

What’s next?