Testing with kotlin.test

Testing with kotlin.test in Kotlin: At the end of a production line stands a quality-control bench.

The Analogy: The Quality-Control Bench

At the end of a production line stands a quality-control bench. Every finished part is checked against a reference master and a set of go/no-go gauges. A good part slides into the gauge and the inspector moves on without a word; a bad part will not fit, trips a flag, and is pulled from the line. The bench is not there to celebrate success -- it is there to catch failure -- so silence means everything is fine and noise means something is wrong. Kotlin's testing works this way: an assertion like assertEquals compares an actual result against a known-good reference, passing silently when they match and throwing an AssertionError when they do not. A test suite is a bench of gauges, and green means every gauge stayed quiet.

Each inspection follows the same three motions: mount the part, run it through the operation, then gauge the result. Set up the inputs, call the function under test, and assert on what came back. This is the arrange-act-assert rhythm, and keeping the three steps distinct makes a test easy to read and easy to trust -- you can see exactly what was fed in, what was run, and what was expected.

Not every gauge measures a dimension. Some verify that a part correctly refuses to proceed -- that a safety cutout trips when it should, that a machine jams on a malformed blank rather than mangling it. Testing has the same tool: assertFailsWith checks that a call throws the exception it is supposed to, so you can assert that bad input is rejected loudly rather than accepted silently. Verifying the failure path is as much a part of quality control as verifying the happy path.

The failure that lets a defective batch ship is an inspector who gauges each part not against the true reference master but against a copy struck from the same flawed mold. The part always matches its clone, so the gauge lights green on every unit even as the whole batch is out of spec. In testing this is the tautological assertion: comparing a function's output against a value computed by that same function, or asserting a result against itself, so the test passes no matter how wrong the code is. A gauge certifies nothing unless its reference is independent of the thing being measured. The reference master must come from outside -- a hand-verified expected value -- or the bench is theatre, quietly approving every defect that walks past it.


Syntax or Core Structure

In a real project, test functions are annotated @Test and use kotlin.test assertions; a passing assertion is silent, a failing one throws AssertionError. The illustrative shape (run by a test runner, not main):

import kotlin.test.Test
import kotlin.test.assertEquals

class MathTest {
    @Test
    fun addsTwoNumbers() {
        assertEquals(5, add(2, 3))   // expected first, actual second
    }
}

The assertions themselves are ordinary functions, so their behaviour can be shown deterministically: a match is silent, a mismatch throws, and assertFailsWith returns the caught exception.

import kotlin.test.assertEquals
import kotlin.test.assertFailsWith

fun add(a: Int, b: Int): Int = a + b

fun main() {
    assertEquals(5, add(2, 3))
    println("equality assertion passed")

    val failure = try {
        assertEquals(9, add(2, 3))
        "no failure"
    } catch (e: AssertionError) {
        "mismatch detected"
    }
    println(failure)

    val ex = assertFailsWith<ArithmeticException> { add(1, 0) / 0 }
    println("threw arithmetic? " + (ex is ArithmeticException))
}

Output:

equality assertion passed
mismatch detected
threw arithmetic? true

The first assertEquals(5, add(2, 3)) matches, so it is silent and "equality assertion passed" prints. The second, assertEquals(9, add(2, 3)), does not match -- 9 versus 5 -- so it throws an AssertionError, caught here and reported as "mismatch detected"; in a real suite this failure would fail the test. The assertFailsWith<ArithmeticException> block runs .../0, which throws, and returns the caught exception so the test can inspect it -- confirming the expected exception type. Note the argument order: assertEquals takes the expected value first and the actual second, which shapes the failure message.


Technical Depth: Assertions, Tables, and Test Doubles

The kotlin.test assertion set

A small vocabulary of assertions covers most checks. The table lists the common ones and what each verifies.

AssertionPasses when
assertEquals(exp, act)exp == act
assertTrue(cond)cond is true
assertFalse(cond)cond is false
assertNull(x)x is null
assertNotNull(x)x is not null
assertFailsWith<E> { }the block throws E

The argument order for assertEquals is expected-then-actual, which determines how the failure message reads ("expected X but was Y"); getting it backwards produces confusing messages even when the test is otherwise correct.

Table-driven testing

When one function must be checked against many inputs, a list of case pairs keeps the test compact and every case explicit.

import kotlin.test.assertEquals

fun isEven(n: Int): Boolean = n % 2 == 0

fun main() {
    val cases = listOf(2 to true, 3 to false, 0 to true, -4 to true)
    var passed = 0
    for ((input, expected) in cases) {
        assertEquals(expected, isEven(input))
        passed += 1
    }
    println("all " + passed + " cases passed")
}

Output:

all 4 cases passed

Each case is an input to expected pair, destructured in the loop. Every case runs assertEquals(expected, isEven(input)); because all four match -- 2 and 0 and -4 are even, 3 is not -- none throws, and the counter reaches 4 to print "all 4 cases passed". Had any case been wrong, its assertEquals would have thrown and stopped the loop, pinpointing the failing input. Table-driven tests make it trivial to add another case: append one pair.

Test doubles remove nondeterminism

Code that depends on the clock, the network, or randomness is untestable until you inject a substitute. A fake implementation of an interface gives the test full control.

interface Clock {
    fun hour(): Int
}

class FakeClock(private val fixed: Int) : Clock {
    override fun hour(): Int = fixed
}

fun greeting(clock: Clock): String =
    if (clock.hour() < 12) "morning" else "afternoon"

fun main() {
    println(greeting(FakeClock(9)))
    println(greeting(FakeClock(15)))
}

Output:

morning
afternoon

greeting depends on the time of day, which would make it nondeterministic if it read the real clock. By depending on a Clock interface instead, the test injects a FakeClock fixed at a chosen hour: 9 yields "morning" (before 12), and 15 yields "afternoon". The fake turns an unpredictable dependency into a controlled input, which is why depending on abstractions rather than concrete system calls is what makes logic testable.

Nullability assertions

assertNull and assertNotNull check presence, and like every assertion they are silent on success and throw on failure.

import kotlin.test.assertNull
import kotlin.test.assertNotNull

fun findUser(id: Int): String? = if (id == 1) "Ada" else null

fun main() {
    assertNotNull(findUser(1))
    assertNull(findUser(2))
    println("presence assertions passed")

    val caught = try {
        assertNull(findUser(1))     // user 1 exists, so this must fail
        "no failure"
    } catch (e: AssertionError) {
        "assertNull failed for a present value"
    }
    println(caught)
}

Output:

presence assertions passed
assertNull failed for a present value

findUser(1) returns "Ada", so assertNotNull passes silently; findUser(2) returns null, so assertNull passes silently, and "presence assertions passed" prints. The second block deliberately asserts that a present value is null: assertNull(findUser(1)) sees "Ada", which is not null, so it throws an AssertionError caught and reported as "assertNull failed for a present value". These assertions read intent clearly -- "this lookup should find nothing", "this lookup should find something" -- more so than a bare assertTrue(x == null).

Asserting on collections

assertContains checks membership in a collection, complementing assertEquals on the size, which together pin down a list's contents.

import kotlin.test.assertContains
import kotlin.test.assertEquals

fun tagsFor(kind: String): List<String> = when (kind) {
    "blog" -> listOf("kotlin", "jvm", "tutorial")
    else -> emptyList()
}

fun main() {
    val tags = tagsFor("blog")
    assertEquals(3, tags.size)
    assertContains(tags, "kotlin")
    println("collection assertions passed")

    val caught = try {
        assertContains(tags, "python")
        "no failure"
    } catch (e: AssertionError) {
        "missing element detected"
    }
    println(caught)
}

Output:

collection assertions passed
missing element detected

tagsFor("blog") returns a three-element list, so assertEquals(3, tags.size) and assertContains(tags, "kotlin") both pass silently and "collection assertions passed" prints. Then assertContains(tags, "python") looks for an element that is not present, throws an AssertionError, and the catch reports "missing element detected". Combining a size assertion with membership assertions is a precise way to state what a collection must contain without over-specifying its exact order when order does not matter.


Real World Example: A Test That Always Passes

A pricing function is meant to apply a percentage discount, but it has a bug: it subtracts the percent as a flat number of cents instead of a percentage. A test was written for it and is green, so everyone assumes the function is correct. The problem is how the test computes its expected value.

import kotlin.test.assertEquals

// BUG: subtracts percent as a flat amount, not a percentage
fun applyDiscount(priceCents: Int, percent: Int): Int = priceCents - percent

fun main() {
    val tautology = try {
        assertEquals(applyDiscount(10000, 20), applyDiscount(10000, 20))
        "tautology test passed"
    } catch (e: AssertionError) {
        "tautology test failed"
    }
    println(tautology)

    val real = try {
        assertEquals(8000, applyDiscount(10000, 20))   // 20% off 10000 = 8000
        "real test passed"
    } catch (e: AssertionError) {
        "real test failed"
    }
    println(real)

    println("actual output: " + applyDiscount(10000, 20))
}

Output:

tautology test passed
real test failed
actual output: 9980

The first test is green, and that green light is a lie. It asserts applyDiscount(10000, 20) equals applyDiscount(10000, 20) -- the function's output against its own output. That comparison is true no matter what the function returns, so "tautology test passed" prints even though the pricing is wrong. This is the inspector gauging a part against a clone of itself.

The second test uses an independent reference. A 20 percent discount on 10000 cents should leave 8000, a value computed by hand and written as a literal, with no involvement from applyDiscount. Asserting assertEquals(8000, applyDiscount(10000, 20)) compares the real expected result against the actual, they differ, and the assertion throws -- "real test failed". The last line shows why: the buggy function returns 9980 (10000 minus 20), not 8000.

The genuine design flaw is the tautological test, whose expected value is derived from the very code under test, so it can never fail and certifies nothing. It provides coverage numbers and a green badge while catching zero defects, which is worse than no test because it manufactures false confidence. The fix is the second test's discipline: the expected value must be an independent reference -- hand-computed, taken from a specification, or produced by a trusted oracle -- never recomputed by the function being tested. The broader limitation is that coverage and green checkmarks measure that code ran, not that it was verified; a test only has value when its assertion could actually fail for a wrong implementation, and the fastest way to confirm that is to briefly break the code and watch the test go red.


Common Mistakes

  1. Writing a tautological assertion. Comparing a function's output to itself, or to an expected value computed by the same code, produces a test that can never fail. The expected value must be independent.
  1. Getting assertEquals argument order wrong. The order is expected-then-actual; reversing it yields backwards failure messages ("expected 5 but was 3" when it is really the other way), confusing whoever debugs it.
  1. Testing implementation instead of behaviour. Asserting on private internals or exact call sequences makes tests brittle to refactoring. Assert on observable outputs and effects.
  1. Leaving system dependencies un-faked. A test that reads the real clock, network, or random source is nondeterministic and flaky. Inject a fake through an interface so inputs are controlled.
  1. Only testing the happy path. Skipping error and edge cases lets failures ship. Use assertFailsWith to verify that bad input is rejected as designed.
  1. Assuming coverage equals correctness. High coverage means code ran during tests, not that it was verified. A line covered by a tautological assertion is not tested.
  1. Sharing mutable state between tests. Tests that depend on each other's leftover state fail intermittently and out of order. Keep each test independent and self-contained.
  1. Never watching the test fail. A test you have not seen go red might be passing for the wrong reason. Break the code briefly to confirm the assertion can actually fail.
  1. Over-mocking until the test mirrors the code. Mocking every collaborator can turn a test into a restatement of the implementation, passing only because it encodes the same steps. Prefer real objects or simple fakes.

Best Practices

  • Derive every expected value independently of the code under test -- by hand, from a spec, or a trusted oracle -- so the assertion can genuinely fail.
  • Follow arrange-act-assert, keeping setup, the call, and the checks visually distinct for readability.
  • Pass assertEquals the expected value first and the actual second, so failure messages read correctly.
  • Inject system dependencies (clock, network, randomness) behind interfaces and substitute fakes to make tests deterministic.
  • Test the failure paths with assertFailsWith, not just the happy path.
  • Prefer table-driven tests for functions checked against many inputs, adding a case with a single pair.
  • Keep tests independent, each arranging its own state, so order and isolation never affect the outcome.
  • Confirm a new test can fail by briefly breaking the code, guarding against tests that are green for the wrong reason.

Practice Exercises

  1. Write add and a main that runs assertEquals(5, add(2, 3)), then a deliberately wrong assertEquals caught as an AssertionError, confirming the pass is silent and the mismatch throws.
  1. Use assertFailsWith to verify that a function throws IllegalArgumentException on invalid input, and confirm the returned exception is of the expected type.
  1. Reproduce the tautological-test flaw: assert a buggy function against its own output so it passes, then rewrite the assertion against an independent literal and show it now fails, exposing the bug.
  1. Make a function depend on a Clock interface, inject a FakeClock fixed at two different hours, and confirm the function's branch is exercised deterministically.