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

Part 11 / Stage 2

Build tooling and testing

Goal: Go from "one file, one kotlinc command" to a real project: a standard src/main/kotlin / src/test/kotlin layout, a dependency (a test framework) that plain kotlinc can't fetch on its own, and real, passing unit tests for a discount function — written with kotlin.test and JUnit 5. Time: ~4 hours · Level: comfortable with Part 5's functions and Part 9's classes

⚠️ A toolchain note before you start. This machine has kotlinc 2.4.21 and JDK 21 (Corretto) installed and verified (see ../../TOOLING.md), but not Gradle — confirmed by running which gradle and gradle -v, both of which came back empty. Every build.gradle.kts in this part is real, standard Kotlin DSL, but it has not been run by gradle on this machine, and every place that matters says so again. Everything marked verified below was actually compiled and run, with the real output pasted in — using kotlinc plus the dependencies Gradle would otherwise fetch for you, downloaded once by hand from Maven Central.

What you will learn

  • Why kotlinc alone stops being enough the moment a project needs more than one source folder and an external dependency
  • The standard Kotlin project layout: src/main/kotlin, src/test/kotlin
  • Gradle with the Kotlin DSL (build.gradle.kts, settings.gradle.kts) — what each block means, read conceptually since Gradle isn't installed here
  • Writing a real, testable module: the discount function from Stage 1, promoted into its own file
  • Unit testing with kotlin.test and JUnit 5: @Test, assertEquals, assertTrue, assertFailsWith, and readable backtick test names
  • Parameterized tests with plain JUnit 5 (@ParameterizedTest, @CsvSource) for boundary values — kotlin.test has no equivalent of its own
  • Running tests from the command line without Gradle, using kotlinc and the JUnit Platform Console launcher — and what gradle test would be doing for you under the hood
  • A real mistake that costs you an afternoon if you don't know about it: reusing one output directory for both main and test compilation
  • ktlint/detekt and an IDE debugger, as concepts you should know exist (neither is installed here, so neither is claimed as verified)

Topics in this part

Practice

Every exercise is a kotlin.test/JUnit 5 test class, not a main() script — the point of this part is testing, so "running" an exercise means compiling it and executing it through the JUnit Platform Console launcher, the same way the README's section 7 does. Each solution file is self-contained (its own package, compiled into its own fresh output directory), so you don't need the full examples/project-layout project to try them.

You'll need the same three jars the README downloaded in section 7, step 0 (junit-platform-console-standalone-1.14.5.jar, kotlin-test-2.3.21.jar, kotlin-test-junit5-2.3.21.jar) plus kotlin-stdlib.jar from your kotlinc install, on the classpath when compiling and running.


Exercise 1: Test a GST function, three ways

Scenario: A withGst function needs real coverage — the normal case, a boundary, and the one input it should refuse. What to do: Write fun withGst(amount: Double): Double that returns amount * 1.18, but requires amount >= 0.0. Write a test class with: an assertEquals test for a normal amount (with a delta), an assertTrue test proving GST strictly increases a positive amount, and an assertFailsWith<IllegalArgumentException> test for a negative amount.

Sample output (--details=summary):

[         4 tests found           ]
[         4 tests successful      ]
[         0 tests failed          ]

💡 Hint: assertTrue(withGst(250.0) > 250.0, "GST should strictly increase a positive amount") — the second argument to assertTrue is the message shown only if it fails.


Exercise 2: Loyalty tiers, including every boundary

Scenario: A loyalty-years-to-discount function has four tiers; the boundaries are exactly where bugs hide. What to do: Write fun loyaltyDiscountPercent(years: Int): Double — >=5 years → 20.0, >=2 → 10.0, >=1 → 5.0, else 0.0 — and require(years >= 0). Write one backtick-named test per boundary (0, 1, 2, 5, and one well above 5 to prove it doesn't keep climbing), plus an assertFailsWith test for a negative input.

Sample output (--details=summary):

[         6 tests found           ]
[         6 tests successful      ]
[         0 tests failed          ]

💡 Hint: test the boundary value itself (loyaltyDiscountPercent(2)), not just one above or below it — that's the value most likely to be off-by-one.


Exercise 3: Parameterized shipping fee

Scenario: A shipping-fee function has three weight tiers; six @Test methods for six weights would be six times the code for the same idea. What to do: Write fun shippingFee(weightKg: Double): Double — <= 1.0 kg → ₹40, <= 5.0 kg → ₹70, else ₹120 — with require(weightKg > 0.0). Write one @ParameterizedTest with @CsvSource covering at least six weights, including both tier boundaries themselves (1.0 and 5.0) and the value just above each (1.01, 5.01).

Sample output (--details=tree, abridged):

├─ ShippingFeeTest ✔
│  └─ shipping fee follows the weight tiers, including the boundary itself(double, double) ✔
│     ├─ 0.5 kg -> ₹40.0 ✔
│     ├─ 1.0 kg -> ₹40.0 ✔
│     ├─ 1.01 kg -> ₹70.0 ✔
│     ├─ 5.0 kg -> ₹70.0 ✔
│     ├─ 5.01 kg -> ₹120.0 ✔
│     └─ 20.0 kg -> ₹120.0 ✔

💡 Hint: @ParameterizedTest(name = "{0} kg -> ₹{1}") substitutes each row's actual values into the name shown in the report.


Exercise 4: A cash-on-delivery eligibility predicate

Scenario: An order qualifies for cash-on-delivery only under specific conditions — exactly the kind of boolean logic that's easy to get subtly wrong. What to do: Write fun isEligibleForCod(orderTotal: Double, pincode: String): Boolean — true only if orderTotal is 0.0..50000.0 and pincode is exactly 6 digits. Write tests using assertTrue/assertFalse (not assertEquals(true, ...)) for: a normal eligible order, an order above the cap, exactly at the cap, a too-short pincode, and a pincode with a letter in it.

Sample output (--details=summary):

[         5 tests found           ]
[         5 tests successful      ]
[         0 tests failed          ]

💡 Hint: pincode.length == 6 && pincode.all { it.isDigit() } — all on a CharSequence checks every character against the predicate.


Exercise 5: Build it as a real two-source-set project

Scenario: Reading about src/main/kotlin/src/test/kotlin and actually keeping them straight across two separate kotlinc invocations are different skills. What to do: Create your own tiny project: src/main/kotlin/.../LoyaltyPoints.kt with fun pointsEarned(amountInr: Double): Int (require(amountInr >= 0.0), one point per full ₹100, rounded down — amountInr / 100 as an Int), and src/test/kotlin/.../LoyaltyPointsTest.kt with tests for a round number, a non-round number (proving it doesn't round up), zero, and a negative amount (assertFailsWith). Compile main into build/classes/main and test into build/classes/test — two separate directories, exactly like the README's section 7 and not like its section 8 mistake — then run everything.

Sample output (--details=tree):

├─ LoyaltyPointsTest ✔
│  ├─ a partial 100 does not round up() ✔
│  ├─ zero spend earns zero points() ✔
│  ├─ negative spend throws() ✔
│  └─ every full 100 rupees earns one point() ✔

💡 Hint: if you see unresolved reference on a function from main that definitely exists, you reused one output directory somewhere — go back and give test its own.


Exercise 6: Read a real failing test, then fix it

Scenario: A test that "should obviously pass" sometimes fails for a Double-shaped reason that has nothing to do with your logic being wrong. What to do: Write fun finalAmount(subtotal: Double, discountPercent: Double, couponPercent: Double): Double (discount, then coupon on what's left, then * 1.18 GST). Write a test that calls assertEquals(902.7, finalAmount(1000.0, 15.0, 10.0)) with no delta argument. Compile and run it, and paste the real failure message you get. Then fix the test (not the function) by adding a delta, and paste the real passing output.

Sample output (buggy, real failure message):

=> org.opentest4j.AssertionFailedError: expected: <902.7> but was: <902.6999999999999>

Sample output (fixed):

[         1 tests found           ]
[         1 tests successful      ]

💡 Hint: 1000.0 - 15% = 850.0, - 10% = 765.0, * 1.18 = 902.7 on paper — but none of those three steps is guaranteed to land on an exactly representable Double along the way.


Exercise 7: A capstone test suite — late fees

Scenario: A library's late fee has two rate tiers and a hard cap — enough moving parts to need every technique from this part in one file. What to do: Write fun lateFeeInr(daysLate: Int): Double — require(daysLate >= 0), ₹2/day for the first 7 days, ₹5/day after that, capped at ₹100 total. Write: a plain @Test for zero days late, an assertFailsWith test for a negative input, a plain @Test proving the cap actually kicks in for a very overdue book, and a @ParameterizedTest/@CsvSource covering at least four days-late values including exactly 7 (the tier boundary).

Sample output (--details=summary):

[         7 tests found           ]
[         7 tests successful      ]
[         0 tests failed          ]

💡 Hint: at exactly 7 days, the fee should still be 7 * 2.0 = 14.0 — it's day 8 where the rate changes, not day 7.

Show the solutions for Part 11 (8 files)

solutions/ex01.kt

package com.stepshala.billing.ex01

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

fun withGst(amount: Double): Double {
    require(amount >= 0.0) { "amount cannot be negative, got $amount" }
    return amount * 1.18
}

class WithGstTest {
    @Test
    fun `GST adds 18 percent`() {
        assertEquals(118.0, withGst(100.0), 0.001)
    }

    @Test
    fun `zero amount stays zero`() {
        assertEquals(0.0, withGst(0.0), 0.001)
    }

    @Test
    fun `amount with GST is always at least as much as the amount`() {
        assertTrue(withGst(250.0) > 250.0, "GST should strictly increase a positive amount")
    }

    @Test
    fun `negative amount throws`() {
        assertFailsWith<IllegalArgumentException> { withGst(-10.0) }
    }
}

solutions/ex02.kt

package com.stepshala.billing.ex02

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

fun loyaltyDiscountPercent(years: Int): Double {
    require(years >= 0) { "years cannot be negative, got $years" }
    return when {
        years >= 5 -> 20.0
        years >= 2 -> 10.0
        years >= 1 -> 5.0
        else -> 0.0
    }
}

class LoyaltyDiscountPercentTest {
    @Test
    fun `brand new customer gets no discount`() {
        assertEquals(0.0, loyaltyDiscountPercent(0))
    }

    @Test
    fun `one year exactly reaches the 5 percent tier`() {
        assertEquals(5.0, loyaltyDiscountPercent(1))
    }

    @Test
    fun `two years exactly reaches the 10 percent tier`() {
        assertEquals(10.0, loyaltyDiscountPercent(2))
    }

    @Test
    fun `five years exactly reaches the 20 percent tier`() {
        assertEquals(20.0, loyaltyDiscountPercent(5))
    }

    @Test
    fun `ten years stays at the top tier, it does not keep climbing`() {
        assertEquals(20.0, loyaltyDiscountPercent(10))
    }

    @Test
    fun `negative years throws`() {
        assertFailsWith<IllegalArgumentException> { loyaltyDiscountPercent(-1) }
    }
}

solutions/ex03.kt

package com.stepshala.billing.ex03

import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
import kotlin.test.assertEquals

fun shippingFee(weightKg: Double): Double {
    require(weightKg > 0.0) { "weightKg must be positive, got $weightKg" }
    return when {
        weightKg <= 1.0 -> 40.0
        weightKg <= 5.0 -> 70.0
        else -> 120.0
    }
}

class ShippingFeeTest {

    @ParameterizedTest(name = "{0} kg -> ₹{1}")
    @CsvSource(
        "0.5, 40.0",
        "1.0, 40.0",
        "1.01, 70.0",
        "5.0, 70.0",
        "5.01, 120.0",
        "20.0, 120.0"
    )
    fun `shipping fee follows the weight tiers, including the boundary itself`(weightKg: Double, expectedFee: Double) {
        assertEquals(expectedFee, shippingFee(weightKg), 0.001)
    }
}

solutions/ex04.kt

package com.stepshala.billing.ex04

import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertTrue

fun isEligibleForCod(orderTotal: Double, pincode: String): Boolean =
    orderTotal in 0.0..50000.0 && pincode.length == 6 && pincode.all { it.isDigit() }

class IsEligibleForCodTest {

    @Test
    fun `a normal order within the cap with a valid pincode is eligible`() {
        assertTrue(isEligibleForCod(1200.0, "411045"))
    }

    @Test
    fun `an order above the cap is not eligible`() {
        assertFalse(isEligibleForCod(50001.0, "411045"))
    }

    @Test
    fun `exactly at the cap is still eligible`() {
        assertTrue(isEligibleForCod(50000.0, "411045"))
    }

    @Test
    fun `a pincode that is too short is rejected`() {
        assertFalse(isEligibleForCod(500.0, "4110"))
    }

    @Test
    fun `a pincode with letters is rejected`() {
        assertFalse(isEligibleForCod(500.0, "41104A"))
    }
}

solutions/ex05-project/src/main/kotlin/com/stepshala/loyalty/LoyaltyPoints.kt

package com.stepshala.loyalty

fun pointsEarned(amountInr: Double): Int {
    require(amountInr >= 0.0) { "amountInr cannot be negative, got $amountInr" }
    return (amountInr / 100).toInt()
}

solutions/ex05-project/src/test/kotlin/com/stepshala/loyalty/LoyaltyPointsTest.kt

package com.stepshala.loyalty

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

class LoyaltyPointsTest {

    @Test
    fun `every full 100 rupees earns one point`() {
        assertEquals(10, pointsEarned(1000.0))
    }

    @Test
    fun `a partial 100 does not round up`() {
        assertEquals(9, pointsEarned(999.0))
    }

    @Test
    fun `zero spend earns zero points`() {
        assertEquals(0, pointsEarned(0.0))
    }

    @Test
    fun `negative spend throws`() {
        assertFailsWith<IllegalArgumentException> { pointsEarned(-5.0) }
    }
}

solutions/ex06.kt

package com.stepshala.billing.ex06

import kotlin.test.Test
import kotlin.test.assertEquals

fun finalAmount(subtotal: Double, discountPercent: Double, couponPercent: Double): Double {
    val afterDiscount = subtotal - subtotal * discountPercent / 100
    val afterCoupon = afterDiscount - afterDiscount * couponPercent / 100
    return afterCoupon * 1.18
}

class FinalAmountTest {
    @Test
    fun `15 percent membership plus 10 percent coupon, then GST`() {
        // FIX: a tiny delta absorbs the Double rounding noise from the chained
        // percentage math -- 902.6999999999999 is close enough to 902.7 to count as equal.
        assertEquals(902.7, finalAmount(1000.0, 15.0, 10.0), 0.001)
    }
}

solutions/ex07.kt

package com.stepshala.billing.ex07

import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource

/**
 * A library late fee: ₹2/day for the first 7 late days, ₹5/day after that, capped at ₹100
 * total so a lost book doesn't rack up an unbounded fine.
 */
fun lateFeeInr(daysLate: Int): Double {
    require(daysLate >= 0) { "daysLate cannot be negative, got $daysLate" }
    val fee = if (daysLate <= 7) {
        daysLate * 2.0
    } else {
        7 * 2.0 + (daysLate - 7) * 5.0
    }
    return fee.coerceAtMost(100.0)
}

class LateFeeInrTest {

    @Test
    fun `no late days means no fee`() {
        assertEquals(0.0, lateFeeInr(0), 0.001)
    }

    @Test
    fun `negative days throws`() {
        assertFailsWith<IllegalArgumentException> { lateFeeInr(-3) }
    }

    @Test
    fun `fee is capped at 100 rupees for a very overdue book`() {
        assertEquals(100.0, lateFeeInr(60), 0.001)
    }

    @ParameterizedTest(name = "{0} days late -> ₹{1}")
    @CsvSource(
        "1, 2.0",
        "7, 14.0",
        "8, 19.0",
        "10, 29.0"
    )
    fun `fee matches the two-tier rate, including right at the 7-day boundary`(daysLate: Int, expectedFee: Double) {
        assertEquals(expectedFee, lateFeeInr(daysLate), 0.001)
    }
}

Common mistakes

Mistake Why it is wrong Fix
assertEquals(902.7, total) on a Double result of chained arithmetic Floating-point math rarely lands on the exact bit pattern you'd compute by hand — this one fails with expected: <902.7> but was: <902.6999999999999> Always pass a delta: assertEquals(902.7, total, 0.001)
Compiling src/main and src/test into the same output directory Silently corrupts Kotlin's cross-file module metadata — section 8's real failure Always use two separate output directories, exactly like Gradle does
Forgetting kotlin-stdlib.jar on the runtime classpath when not using -include-runtime NoClassDefFoundError: kotlin/jvm/internal/Intrinsics (or similar) at the moment any Kotlin null-check or stdlib call executes Add kotlin-stdlib.jar to the --classpath when running tests or compiled code directly
Expecting kotlin.test to have @ParameterizedTest It's a JUnit 5-only feature; kotlin.test is a minimal, engine-agnostic facade Import org.junit.jupiter.params.* directly alongside kotlin.test
Writing membershipDiscountPercent("platinum") and expecting 0.0 back The function throws on an unknown tier on purpose, so bad input fails loudly instead of silently billing 0.0 Test the throw with assertFailsWith, don't assume a silent fallback
Treating an unverified build.gradle.kts as if gradle test had been run This course doesn't have Gradle installed — the file is real syntax, not a tested result Trust the kotlinc + JUnit Platform Console transcript in section 7 instead

Quick recap

  • kotlinc alone can't fetch a dependency from Maven Central — that's a build tool's job, and Gradle (with the Kotlin DSL) is the standard one for Kotlin projects.
  • The conventional layout is src/main/kotlin for code, src/test/kotlin for tests — a separate source set that can see main but never the other way around.
  • kotlin.test gives @Test/assertEquals/assertTrue/assertFailsWith as an engine-agnostic facade; @ParameterizedTest/@CsvSource are JUnit 5-only, used directly.
  • assertEquals on Double values needs a delta argument — chained percentage math rarely lands on an exact bit pattern.
  • Without Gradle, kotlinc + the JUnit Platform Console standalone launcher runs the exact same tests gradle test would, as long as main and test compile into separate output directories.
  • ktlint/detekt and an IDE debugger are real, standard tools worth knowing about, even though neither was installed or run on this machine.

Checklist

  • I can explain why kotlinc alone isn't enough once a project needs a dependency.
  • I laid out a project as src/main/kotlin / src/test/kotlin myself.
  • I can read a build.gradle.kts's plugins/repositories/dependencies/tasks.test blocks and say what each one is for.
  • I wrote kotlin.test tests using @Test, assertEquals (with a delta), assertTrue, and assertFailsWith.
  • I wrote a @ParameterizedTest with @CsvSource covering more than one input.
  • I ran the whole suite myself with kotlinc and the JUnit Platform Console launcher and got "10 tests successful."
  • I reproduced the same-output-directory mistake myself and understood why it broke.

Search the guide