Kotlin Tutorial · Kotlin Projects · Lesson 29 of 31

Kotlin Testing

Write unit tests with kotlin.test and JUnit, assert results and exceptions, and test coroutines.

Create a free account to save this page, take notes and track your progress. Sign in

kotlin.test

kotlin.test gives multiplatform assertions (assertEquals, assertTrue, assertFailsWith) and annotations (@Test). With Gradle, add testImplementation(kotlin("test")) and put tests in src/test/kotlin; run them with ./gradlew test.

import kotlin.test.*

class PriceTest {
    @Test
    fun appliesDiscount() {
        assertEquals(80.0, discounted(100.0, 20))
    }

    @Test
    fun rejectsNegativePercent() {
        assertFailsWith<IllegalArgumentException> { discounted(100.0, -5) }
    }
}

The assertions also work outside a test runner, which shows what they check:

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

fun discounted(price: Double, percent: Int): Double {
    require(percent in 0..100) { "percent must be 0..100" }
    return price * (100 - percent) / 100
}

fun main() {
    assertEquals(80.0, discounted(100.0, 20))
    println("appliesDiscount passed")
    val e = assertFailsWith<IllegalArgumentException> { discounted(100.0, -5) }
    println("rejectsNegativePercent passed: ${e.message}")
    val failure = runCatching { assertEquals(90.0, discounted(100.0, 20)) }.exceptionOrNull()
    println("a failing assertion says: ${failure?.message}")
}

Output

appliesDiscount passed
rejectsNegativePercent passed: percent must be 0..100
a failing assertion says: Expected <90.0>, actual <80.0>.

Run this on your computer — see “Get Started” for setup.

For coroutines, kotlinx-coroutines-test provides runTest, which skips delays with virtual time so tests stay fast.

Test yourself

Which assertion checks that code throws a specific exception?

  1. assertThrows()
  2. assertFailsWith<T> { }
  3. expectError()
  4. assertNull()
Show answer

Answer: assertFailsWith<T> { }

Was this page helpful?