Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Kotlin
Stage 5: Specialization

Part 11 / Topic 5 of 9

Unit tests with kotlin.test and JUnit 5

kotlin.test is a thin, platform-independent facade: @Test, assertEquals, assertTrue, assertFailsWith, written once, that maps onto whichever test engine the project actually uses underneath — here, JUnit 5, via the kotlin-test-junit5 dependency.

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue

class DiscountCalculatorTest {

    @Test
    fun `gold member gets 15 percent off before GST`() {
        val total = finalBill(subtotal = 1000.0, membershipDiscountPercent = membershipDiscountPercent("gold"), applyGst = false)
        assertEquals(850.0, total, 0.001)
    }

    @Test
    fun `final bill never exceeds the original subtotal when GST is off`() {
        val total = finalBill(subtotal = 2000.0, membershipDiscountPercent = 5.0, couponPercent = 5.0, applyGst = false)
        assertTrue(total < 2000.0, "expected a discounted total below the subtotal, got $total")
    }

    @Test
    fun `unknown membership tier throws`() {
        assertFailsWith<IllegalArgumentException> { membershipDiscountPercent("platinum") }
    }
}

A few conventions worth adopting immediately:

  • Backtick test names (`gold member gets 15 percent off before GST`()) are a real Kotlin feature — a function name can be almost any string between backticks. A test report that says "unknown membership tier throws" instead of testUnknownTierThrows is worth the slightly unusual syntax.
  • assertEquals(expected, actual, delta) takes a third argument for Double comparisons — section 8 shows exactly why that's not optional, with a real crash.
  • assertFailsWith<ExceptionType> { ... } is how you assert that code should throw — without it, an exception just fails the test for the wrong reason.

The full suite (examples/project-layout/src/test/kotlin/com/stepshala/billing/DiscountCalculatorTest.kt) has seven tests covering the happy path, GST ordering, a Double comparison, the IllegalArgumentException paths for an unknown tier and a negative subtotal, and a coupon above 100% being clamped instead of producing a negative total.

Done here? The practice set for Part 11 — including the solutions — is on the part page.

Search the guide