Explain it simply
Testing in plain language
A test is a small program that calls your code with known input and checks that the result is what you expect. Instead of running the app and clicking around to see whether a change broke something, you run the tests and get a pass or fail in seconds. Think of a smoke detector: it does nothing while all is well, it is cheap to keep, and it tells you loudly and early when something is wrong.
In Kotlin projects the standard pair is kotlin.test, a small library of annotations and assertion functions that works on every platform, and JUnit, the engine on the JVM that finds your test functions, runs them one by one and prints the report. Gradle starts that engine when you run ./gradlew test.
Problem → Why → Solution
The problem: a pricing rule checked by hand
You change a pricing rule on Friday afternoon. Checking it by hand means launching the app, adding an item, applying a coupon, trying 0%, 100% and a negative percentage, and doing it all again after the next change. Nobody repeats those steps every time, so a bug slips through: a 150% coupon makes the price negative and the shop pays its customers. Manual checks also leave no record, so the next developer does not know which cases mattered.
fun applyDiscount(priceCents: Int, percent: Int): Int {
return priceCents - priceCents * percent / 100
}
fun main() {
// "testing" by eye: run it and squint at the output
println(applyDiscount(1000, 25)) // 750, looks fine
println(applyDiscount(1000, 150)) // -500, nobody notices
}A test makes a manual check repeatable
A test turns a one-off manual check into a repeatable, named, automatic one. Each test records an expectation you once cared about, and the whole suite runs in seconds on every change, so a bug is reported next to the change that caused it instead of weeks later by a customer.
Core concept: frameworks, assertions and deterministic tests
You could write checks yourself, as the worked example does, but a framework does the repetitive parts: it discovers every function marked @Test, runs each one in a fresh instance of the test class so tests cannot leak state into each other, catches the failure of one test without stopping the others, and prints a report with the name of every failing test and its expected and actual values.
kotlin.test provides the vocabulary: assertEquals(expected, actual) compares values, assertTrue and assertFalse check conditions, assertNull and assertNotNull check nullability, assertContentEquals compares collections element by element, and assertFailsWith<T> { ... } runs a block, fails if it does not throw T and returns the exception so you can inspect its message. Mind the argument order: expected first, actual second, because the failure message says expected: <800> but was: <750> and a swapped order makes that sentence lie.
| Function | Use it to |
|---|---|
| assertEquals(expected, actual) | compare two values with equals |
| assertTrue(condition) / assertFalse | check a boolean condition |
| assertNull(x) / assertNotNull(x) | check that a value is or is not null |
| assertContentEquals(a, b) | compare collections or arrays element by element |
| assertFailsWith<T> { ... } | check that a block throws T, and inspect the exception |
A good test has three parts: arrange (create the input and fakes), act (call the code under test once) and assert (check one behaviour). Name it after that behaviour, such as rejects percent above 100; on the JVM Kotlin lets you write the name between backticks so the report reads like a sentence. Choose cases deliberately: the normal path, the boundaries (0, 1, the maximum, one past the maximum), empty and null inputs, and each failure the function promises (an exception, a null, an error value).
Tests must be deterministic: same input, same result, every run. Anything that varies, such as the current time, random numbers, the network, files or leftovers from other tests, makes a test flaky, and flaky tests get ignored. The cure is to pass such things in: a Clock or Random as a parameter, a fake repository instead of a real database. For suspend functions, runTest from kotlinx-coroutines-test runs the test body in a controlled scheduler with virtual time, so delay(1_000) finishes at once instead of waiting a second.
- Arrange: build input and fakes
- Act: call the code under test once
- Assert: compare result to expectation
- Runner: report each result, keep going
If a test can never fail, it is not a test: prove it by breaking the code on purpose and watching it go red.
General pattern
import kotlin.test.Test
import kotlin.test.assertEquals
class SubjectTest {
@Test
fun `behaviour described in plain words`() {
val input = anInput() // arrange
val result = subject(input) // act
assertEquals(expected, result) // assert
}
}Mark each test function with @Test and name it after the behaviour. Inside, follow arrange, act, assert, and put expected first in assertEquals.
Worked example: a tiny test framework and its tests
kotlin.test and JUnit are not available in a single-file program, so this example builds the same ideas in about fifty lines: assertEquals and assertFailsWith as ordinary functions that throw, and a TestRunner that registers named tests, runs each one, catches failures and reports. Seeing how little magic there is makes the real tools easier to trust. The function under test is applyDiscount, which uses require() to check the percent.
Real tools, same shape
In a Gradle project you would not write the runner yourself. A later section shows similar tests with kotlin.test and JUnit, where @Test replaces runner.test(...) and Gradle's test task replaces runAll().
class AssertionFailed(message: String) : Exception(message)
fun <T> assertEquals(expected: T, actual: T) {
if (expected != actual) {
throw AssertionFailed("expected <$expected> but was <$actual>")
}
}
inline fun <reified T : Throwable> assertFailsWith(block: () -> Unit): T {
val wanted = T::class.simpleName
try {
block()
} catch (e: Throwable) {
if (e is T) return e
throw AssertionFailed("expected $wanted but got ${e::class.simpleName}")
}
throw AssertionFailed("expected $wanted but nothing was thrown")
}
fun applyDiscount(priceCents: Int, percent: Int): Int {
require(percent in 0..100) { "percent must be 0..100 but was $percent" }
return priceCents - priceCents * percent / 100
}
class TestRunner {
private val tests = mutableListOf<Pair<String, () -> Unit>>()
fun test(name: String, body: () -> Unit) {
tests += name to body
}
fun runAll(): Int {
var failures = 0
for ((name, body) in tests) {
try {
body()
println("PASS $name")
} catch (e: AssertionFailed) {
failures++
println("FAIL $name: ${e.message}")
}
}
println("${tests.size - failures} passed, $failures failed")
return failures
}
}
fun main() {
val runner = TestRunner()
runner.test("zero percent keeps the full price") {
assertEquals(1000, applyDiscount(1000, 0))
}
runner.test("25 percent off 1000 is 750") {
assertEquals(750, applyDiscount(1000, 25))
}
runner.test("100 percent makes it free") {
assertEquals(0, applyDiscount(999, 100))
}
runner.test("rejects percent above 100") {
val error = assertFailsWith<IllegalArgumentException> { applyDiscount(1000, 101) }
assertEquals("percent must be 0..100 but was 101", error.message)
}
val failures = runner.runAll()
check(failures == 0) { "some tests failed" }
}Code breakdown
- A failed assertion is an exception
throw AssertionFailed("expected <$expected> but was <$actual>")An assertion simply throws an exception when two values differ; there is no magic. The message contains both expected and actual, so a failure shows at once what was compared with what.
- assertFailsWith
inline fun <reified T : Throwable> assertFailsWith(block: () -> Unit): T {Thanks to reified T the function knows T's class at runtime and can test 'is T'. If the block throws the right exception it is returned; if nothing is thrown, or another type is, the function fails with AssertionFailed.
- Register tests as data
tests += name to bodyEach test is a name plus a lambda, so it can be stored in a list and run later. JUnit finding @Test functions through reflection is the same idea.
- Isolate each failure
} catch (e: AssertionFailed) {When a test fails, the runner catches it, counts it and moves on to the next one, so a single failure does not hide the other tests.
- A test is an ordinary call
assertEquals(750, applyDiscount(1000, 25))Expected 750 comes first and the call under test second. 25% off 1000 is 250, so 750 remains: the number comes from working it out by hand, not from copying the function's output.
- Fail the whole run
check(failures == 0) { "some tests failed" }If any test failed, the program ends with an exception, so a CI server can look at the exit status and fail the build, which is what Gradle's test task does as well.
PASS zero percent keeps the full price
PASS 25 percent off 1000 is 750
PASS 100 percent makes it free
PASS rejects percent above 100
4 passed, 0 failed- Compile src/main/kotlin and src/test/kotlin
- JUnit scans the test classes for @Test functions
- Each test runs in a fresh instance of the class
- Failures are recorded and the other tests still run
- Gradle prints a summary and writes an HTML report
Similar tests with kotlin.test and JUnit
The class below writes tests like those of the worked example with kotlin.test. @Test takes the place of runner.test(...), and assertFailsWith<T> returns the exception so you can check its message. A deliberately wrong assertEquals(800, applyDiscount(1000, 25)) is reported as expected: <800> but was: <750>.
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class DiscountTest {
@Test
fun `zero percent keeps the full price`() {
assertEquals(1000, applyDiscount(1000, 0))
}
@Test
fun `25 percent off 1000 is 750`() {
assertEquals(750, applyDiscount(1000, 25))
}
@Test
fun `rejects percent above 100`() {
val error = assertFailsWith<IllegalArgumentException> {
applyDiscount(1000, 101)
}
assertEquals("percent must be 0..100 but was 101", error.message)
}
}On the Gradle side, kotlin("test") goes on the test classpath and the test task is told to run on the JUnit Platform. Test files live in src/test/kotlin, and after ./gradlew test you can read the result in the terminal and in build/reports/tests/test/index.html.
dependencies {
testImplementation(kotlin("test"))
}
tasks.test {
useJUnitPlatform()
}Cases worth testing
The choice of cases matters more than the number of tests. Bugs seldom live on the normal path; they live at the edges of a rule. The table shows the kinds of case worth writing for applyDiscount.
| Kind of case | Example for applyDiscount |
|---|---|
| Normal path | 25% off 1000 gives 750 |
| Lower boundary | 0% leaves the price unchanged |
| Upper boundary | 100% gives 0 |
| One step outside | -1 and 101 throw IllegalArgumentException |
| Zero or empty input | a price of 0 gives 0 |
Testing suspend functions with runTest
An ordinary test function cannot call a suspend function, and testing code that contains delay through runBlocking is slow because it really waits. runTest from kotlinx-coroutines-test uses virtual time, so even a test around delay(1_000) finishes in a few milliseconds. Add the dependency as testImplementation with the same version as kotlinx-coroutines-core.
import kotlinx.coroutines.delay
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
suspend fun slowGreeting(): String {
delay(1_000)
return "hello"
}
class SlowGreeterTest {
@Test
fun `returns the greeting without really waiting a second`() = runTest {
assertEquals("hello", slowGreeting())
}
}In real projects
Where tests show up in real projects
In professional projects tests are part of the code, not extra work. A change without tests has a hard time getting into a pull request, because reviewers rely on the test results instead of re-running the code by hand.
- CI: on every pull request the CI server runs ./gradlew test (or build) and blocks the merge when it fails. The report is in build/reports/tests/test/index.html.
- Android: fast local unit tests that run on the JVM live in src/test, and instrumented tests that run on a device live in src/androidTest.
- Spring Boot and Ktor: they build on JUnit 5 and offer helpers to exercise controllers without starting a real server; project generators usually add the test dependencies for you.
- Kotlin Multiplatform: tests in commonTest run on every target, so you can check that shared logic behaves the same on every platform.
- Fixing bugs: write a red test that shows the bug first and fix it afterwards, so the bug is checked for ever after.
Common mistakes
Common mistakes with tests
A test that can never fail
Writing try { f() } catch (e: SomeException) { } with no assertion leaves the test green whether or not an exception occurs. In the code below buggyDiscount accepts 150%, yet the weak test is green, while a check like assertFailsWith goes red with 'expected IllegalArgumentException but nothing was thrown'. When you expect an exception, use assertFailsWith.
Swapping expected and actual
Writing assertEquals(applyDiscount(1000, 25), 800) still fails correctly, but the message says 'expected: <750> but was: <800>'. You expected 800 and the code produced 750, so the message reads backwards and wastes debugging time. Always put expected first.
Using the clock, randomness or the network directly
A test that depends on the current time, an unseeded Random or the real network fails one run in twenty for no visible reason. Pass a Clock or a Random in as a parameter and use a fake in the test, one that always returns the same thing.
Using real delays in coroutine tests
Waiting on Thread.sleep or a delay(2_000) inside runBlocking slows the suite down and makes it flaky because it depends on real time. Use runTest and its virtual time.
fun buggyDiscount(priceCents: Int, percent: Int) = priceCents - priceCents * percent / 100
inline fun <reified T : Throwable> expectFailure(block: () -> Unit) {
try {
block()
} catch (e: Throwable) {
if (e is T) return
throw e
}
throw AssertionError("expected ${T::class.simpleName} but nothing was thrown")
}
fun main() {
try {
buggyDiscount(1000, 150)
} catch (e: IllegalArgumentException) {
println("never printed")
}
println("weak test: green, although 150 percent was accepted")
try {
expectFailure<IllegalArgumentException> { buggyDiscount(1000, 150) }
} catch (e: AssertionError) {
println("real test: red -> ${e.message}")
}
}Best practices
Best practices
- Test behaviour, not implementation details, so refactoring does not break the tests.
- Give each test one behaviour and a sentence-like name, so a failure tells you what broke from the name alone.
- Keep tests fast and independent, so running them on every pull request stays cheap.
- Work out expected values by hand; copying the output of the function under test would bless its bugs as correct.
Mini challenge
Mini challenge: build median with tests
Write a median function that returns the median of a list of Ints. An empty list must throw IllegalArgumentException through require(), and the function must not reorder the list it is given. Then write the test code in main: collect the cases in a table and verify them with check().
- median(values) returns a Double: the middle value for an odd count, the mean of the two middle values for an even count
- An empty list throws IllegalArgumentException through require(), with a clear message
- The input list must not be changed (use the fact that sorted() returns a new list)
- Check single-value, odd-count, even-count and negative-number cases through a table and print PASS for each
// TODO: require() a non-empty list, sort a COPY, then pick the middle value
// (odd size) or the mean of the two middle values (even size)
fun median(values: List<Int>): Double {
TODO()
}
// TODO: run block and return the message of the IllegalArgumentException it
// throws, or null when nothing is thrown
fun failureMessage(block: () -> Unit): String? {
TODO()
}
fun main() {
// TODO: a table of (name, input, expected) cases: one value, odd count,
// even count, negative numbers; check() each result and print PASS <name>
// TODO: check() that median does not reorder a mutable input list
// TODO: check() the exact message produced for an empty list
}Expected: It prints six lines: PASS single value, PASS odd count, PASS even count, PASS negative numbers, PASS input is not modified and PASS empty list is rejected. If any check is wrong, the program throws an exception with its message.
Show hint
For the case table you can nest pairs, listOf("name" to (listOf(3, 1, 2) to 2.0)), and destructure with for ((name, case) in cases). In failureMessage use try / catch (e: IllegalArgumentException) and return null after block(). For an even size the two middle values are sorted[mid - 1] and sorted[mid].
Show solution
fun median(values: List<Int>): Double {
require(values.isNotEmpty()) { "median of an empty list is undefined" }
val sorted = values.sorted()
val mid = sorted.size / 2
return if (sorted.size % 2 == 1) {
sorted[mid].toDouble()
} else {
(sorted[mid - 1] + sorted[mid]) / 2.0
}
}
fun failureMessage(block: () -> Unit): String? =
try {
block()
null
} catch (e: IllegalArgumentException) {
e.message
}
fun main() {
val cases = listOf(
"single value" to (listOf(7) to 7.0),
"odd count" to (listOf(3, 1, 2) to 2.0),
"even count" to (listOf(4, 1, 3, 2) to 2.5),
"negative numbers" to (listOf(-5, -1, -3) to -3.0),
)
for ((name, case) in cases) {
val (input, expected) = case
val actual = median(input)
check(actual == expected) { "$name: expected $expected but was $actual" }
println("PASS $name")
}
val input = mutableListOf(9, 1, 5)
median(input)
check(input == listOf(9, 1, 5)) { "median must not reorder its input" }
println("PASS input is not modified")
val message = failureMessage { median(emptyList()) }
check(message == "median of an empty list is undefined")
println("PASS empty list is rejected")
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A test framework finds @Test functions, runs each in isolation and reports the failures.
- kotlin.test's assertEquals(expected, actual) and assertFailsWith<T> are the core assertions; always put expected first.
- Structure tests as arrange, act, assert and choose the normal path, boundaries and failure cases.
- In Gradle use testImplementation(kotlin("test")) and useJUnitPlatform(), and keep tests deterministic with fakes and runTest.
Test code using Kotlin and JUnit — Kotlin