Getting started with JUnit Tests

Let’s test our Koin injected application

Gradle Setup

First, add the Koin dependency like below:

// Add Jcenter to your repositories if needed
repositories {
dependencies {
    // Koin testing tools
    testcompile 'org.koin:koin-test:0.9.3'

Declared dependencies

Let’s create a Repository to provide some data (giveHello()):

interface Repository {
    fun giveHello()

class MyRepository() : Repository {
    override fun giveHello() = "Hello Koin"

A Presenter class, for consuming this data:

// Use Repository - injected by constructor by Koin
class MyPresenter(val repository : Repository){
    fun sayHello() = repository.giveHello()

Use the applicationContext function to declare a module. Let’s declare our first component:

// Koin module
val myModule : Module = applicationContext {
    provide { MyPresenter(get()) } // get() will resolve Repository instance
    provide { MyRepository() as Repository }

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 FirstTest : KoinTest {

    val presenter : MyPresenter by inject()
    val repository : Repository by inject()

    fun before(){

    fun after(){

    fun testSayHello() {
        assertEquals(repository.giveHello(), presenter.sayHello())

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

What’s Next?

You have finished this starting tutorial. Below are some topics for further reading:

General Topics