Testing Kotlin: JUnit 5 and MockK
Harry
· 23 Sep 2026
· 3 views
Log in to track your progress and mark lessons complete.
Sponsored
kotlin.test Basics
import kotlin.test.*
class DiscountTest {
@Test fun tenPercentOff() {
assertEquals(450, discount(500, 10))
assertTrue(isAdult(21))
assertFailsWith<IllegalArgumentException> { discount(-5, 10) }
}
}JUnit 5 Power
- @ParameterizedTest with @ValueSource/@CsvSource - one test, many rows.
- @Nested inner classes - group by behaviour with readable names.
- assertThrows - exception paths covered.
MockK for Mocks
val repo = mockk<BookRepository>()
every { repo.findBySlug("x") } returns book
verify { repo.findBySlug("x") }MockK understands Kotlin (object mocks, coEvery for suspend functions) better than plain Mockito.
Testing Coroutines
@Test fun loadsTotal() = runTest {
assertEquals(998, fetchTotal())
}runTest executes suspend code deterministically with virtual time - no sleeps, no flakes.
Key Points
- kotlin.test plus JUnit 5 covers units cleanly.
- MockK for Kotlin-idiomatic mocks, coEvery for suspend.
- runTest makes coroutine tests fast and stable.