androidengineers.Book a session

Testing in Kotlin

TDD workflow in Kotlin

article15 minHard

Let a failing example guide one behavior change

Test-driven development cycles through a failing test, the smallest correct implementation, and refactoring while tests remain green. The failure should demonstrate missing behavior, not a broken test environment.

import kotlin.test.*

class SlugTest {
    @Test fun normalizesOneTitle() {
        assertEquals("kotlin-basics", slug(" Kotlin Basics "))
    }
}

fun slug(title: String): String = title.trim().lowercase().replace(" ", "-")

This implementation satisfies only the current simple rule. A next test for repeated spaces should force a clearer whitespace policy. Another for punctuation should require deciding whether punctuation is removed, encoded, or rejected. Do not silently assume this toy slug function is production-ready.

Exercise

Add one failing case at a time for repeated whitespace, blank input, and punctuation. Write down the intended policy before changing the implementation. Refactor only after the behavioral tests pass.

Check: avoid adding tests merely to mirror private methods; a public behavior should remain verifiable after internal structure changes.

Reference: Kotlin test tooling

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
TDD workflow in Kotlin | Kotlin Core Programming | Android Engineers