Testing Kotlin: JUnit 5 and MockK

Harry · 23 Sep 2026 · 3 views
Log in to track your progress and mark lessons complete.

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.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in