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.
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:
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?
assertThrows()assertFailsWith<T> { }expectError()assertNull()
Show answer
Answer: assertFailsWith<T> { }