Unit testing your Kotlin code

Let’s start with our simple little Calculator class

package com.putridparrot

class Calculator {
    fun add(a : Int, b : Int): Int{
        return a + b
    }
}

Creating our unit test(s)

Add a Kotlin class file and copy the following code into it

package com.putridparrot

import kotlin.test.assertEquals
import org.junit.Test as test

class TestCalculator() {
    @test fun testAdd() {
        val c = Calculator()

        assertEquals(c.add(5, 2), 7)
    }
}

IntelliJ will help us add the dependencies, but if you need to add them manually, select File | Project Structure and in the Project Settings | Modules we need to add JUnit4.

Obviously we’re able to import Java compiled code into our project as Kotlin and Java share the JVM bytecode, so in this instance we’re using JUnit’s Test annotation (renaming to test for this example), we’re also using Kotlin, test assertions.

That’s all there is to it.