Writing Unit Tests in Kotlin
Unit testing in Kotlin is pretty simple and easy, this is usually done with the kotlin.test library, which is based on JUnit 5, you can of course, use just JUnit 5 but kotlin.test has better support and documentation. In this tutorial, we will be using kotlin.test
Let's say we want to test this code:
class Calculator {
fun add(a: Int, b: Int): Int {
return a + b
}
fun subtract(a: Int, b: Int): Int {
return a - b
}
}
Writing the tests
First, we'll need to import the @Test annotation and the assertEquals function
import kotlin.test.Test
import kotlin.test.assertEquals
then we'll write the actual tests
class CalculatorTest {
private val calc = Calculator()
@Test
fun `sum method`() {
assertEquals(5, calc.add(2,3))
}
@Test
fun `subtract method`() {
assertEquals(5, calc.subtract(10, 5))
}
}
I won't waste time going into details, but there are a few things of note here: the tests are annotated with @Test, they are grouped in a class, and their names are surrounded in backticks.
Backticks are syntax which allows reserved characters and other things like spaces to be in function or variable names, which is usually not allowed and helps test names be more descriptive.
Setup and teardown functions
In Kotlin, traditional setup and teardown functions do not exist, although a couple of common approaches to reusing instances of classes, and other such things are:
- Setting a class property to whatever value we need:
class CalculatorTest {
private val calc = Calculator()
// tests
}
- Using an
init {}block.
class CalculatorTest {
private val calc: Calculator
init {
calc = Calculator()
}
// tests
}
This is a simple example, but an init {} block is normally used when there's more complicated logic that goes into actually initializing variables.
Running the tests
Running tests is pretty simple, you can either run them through the command line using: ./gradlew check, or through your IDE's GUI.
Relevant links and documentation
- kotlin.test API Docs - Contains API Documentation for a variety of useful annotations and assertions.
- MockK - A Kotlin mocking library.
- kotest - An alternative testing framework.
- strikt - A assertions library, which provides assertions that are similar to Jest.
