Skip to content
AgileLogics
6 min read

Testing with kotlin.test and JUnit

Prerequisites: Gradle basics, Classes and objects

A test is code that checks your other code works. Once written, it runs in a fraction of a second every time you change something, catching mistakes before your users do.

Kotlin's kotlin.test library provides assertions and annotations that run on JUnit 5 on the JVM.

Setup

// build.gradle.kts
dependencies {
    testImplementation(kotlin("test"))
}

tasks.test {
    useJUnitPlatform()
}

The code under test

// src/main/kotlin/Cart.kt
class Cart {
    private val items = mutableListOf<Pair<String, Int>>()

    fun add(name: String, price: Int) {
        require(price > 0) { "price must be positive" }
        items += name to price
    }

    val total: Int get() = items.sumOf { it.second }
    val isEmpty: Boolean get() = items.isEmpty()
}

The tests

// src/test/kotlin/CartTest.kt
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue

class CartTest {
    @Test
    fun `starts empty`() {
        val cart = Cart()
        assertTrue(cart.isEmpty)
        assertEquals(0, cart.total)
    }

    @Test
    fun `total adds up prices`() {
        val cart = Cart()
        cart.add("book", 12)
        cart.add("pen", 3)
        assertEquals(15, cart.total)
    }

    @Test
    fun `rejects non-positive prices`() {
        val error = assertFailsWith<IllegalArgumentException> {
            Cart().add("free", 0)
        }
        assertEquals("price must be positive", error.message)
    }
}
$ ./gradlew test

BUILD SUCCESSFUL in 3s
  • @Test marks a test function.
  • Kotlin allows function names in backticks with spaces — popular for readable test names.
  • assertEquals(expected, actual) is the most common assertion; others include assertTrue, assertNull, assertContains, and assertFailsWith.
  • Each test creates its own Cart, so tests don't affect each other.

When a test fails, Gradle reports the test name and a message such as expected:<15> but was:<12>; IntelliJ shows a clickable diff. Run a single test from the green ▶ in the gutter.

Other tools you'll meet

  • Kotest — a popular Kotlin-first test framework with a readable specification style and property-based testing.
  • MockK — creates fake versions of classes and interfaces for tests.
  • kotlinx-coroutines-test — for testing coroutine code (Level 3).

Common mistakes

  • Swapping assertEquals arguments. It's (expected, actual) — the wrong order makes failure messages misleading.
  • Forgetting useJUnitPlatform(), so Gradle finds no tests and still reports success.