androidengineers.Book a session

Testing in Kotlin

kotlin.test & Assertions

article15 minHard

Choose assertions that explain the failed promise

kotlin.test provides assertion functions usable with platform-specific test integrations. Prefer specific assertions for equality, nullability, collections, and exceptions over one generic Boolean check.

import kotlin.test.*

fun positive(text: String): Int? = text.toIntOrNull()?.takeIf { it > 0 }

class PositiveTest {
    @Test fun acceptsPositiveInput() { assertEquals(25, positive("25")) }
    @Test fun rejectsZero() { assertNull(positive("0")) }
    @Test fun comparesArrayContents() {
        assertContentEquals(intArrayOf(1, 2), intArrayOf(1, 2))
    }
}

Keep expected and actual arguments in their documented order so failure messages remain useful. Arrays need content assertions when element equality is the contract. Floating-point calculations may need an explicit tolerance derived from the problem rather than arbitrary exact equality.

Exercise

Add malformed input and integer-overflow cases. Test a function that intentionally throws and inspect its exception type with assertFailsWith.

Check: avoid catching an exception manually and forgetting to fail when no exception occurs; the dedicated assertion handles that case.

Reference: kotlin.test

YOUR LEARNING JOURNEY

0 of 110 available lessons completed

Progress saved in this browser. No account needed.
kotlin.test & Assertions | Kotlin Core Programming | Android Engineers