Skip to Content
Course content

156: Parameterized Tests in Kotlin

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've spent a fair amount of time reviewing PRs where the test suite looks like a copy-paste accident. You know the pattern: ten different test methods that are identical except for one string input and one boolean expectation. It usually happens when we're testing validation logic or business rules where the "edge cases" start piling up. It's not technically "wrong"—the tests pass, and the coverage is there—but it's a maintenance nightmare. If you change a constructor or a method signature, you're suddenly updating ten different places for the same logic.

The Wall of Repetition

Let's say we're building a PasswordValidator. We have a few rules: it needs to be at least 8 characters, contain a digit, and contain a special character. In a naive approach, you might write your tests like this:

class PasswordValidatorTest {
    private val validator = PasswordValidator()

    @Test
    fun `too short password should be invalid`() {
        assertFalse(validator.isValid("Ab1!"))
    }

    @Test
    fun `password without digit should be invalid`() {
        assertFalse(validator.isValid("Abcdefgh!"))
    }

    @Test
    fun `password without special char should be invalid`() {
        assertFalse(validator.isValid("Abcdefg1"))
    }

    @Test
    fun `valid password should be valid`() {
        assertTrue(validator.isValid("SafePass123!"))
    }
}

This is what I call the "Wall of Repetition." It’s easy to write the first two, but by the fifth or sixth edge case, you're just duplicating boilerplate. The actual intent of the test—verifying that various inputs produce a specific result—is buried under the noise of method declarations and repeated assertions.

Consolidating Logic with Parameterized Tests

If you're using JUnit 5 (which you should be in a modern Kotlin project), there's a much cleaner way to handle this using @ParameterizedTest. Instead of writing a new method for every single case, you write one test template and feed it a stream of data. If you only need to test a single input that should all result in the same outcome, @ValueSource is your best friend.

Imagine we just want to test a bunch of invalid passwords. We can collapse those first three tests into one:

@ParameterizedTest
@ValueSource(strings = ["Ab1!", "Abcdefgh!", "Abcdefg1", ""])
fun `invalid passwords should return false`(password: String) {
    assertFalse(validator.isValid(password))
}

Now the test is a data table. If I find a new edge case tomorrow, I just add one string to the array. I don't have to write a new function, name it, and add another @Test annotation. It's cleaner, and it forces you to think about your test cases as a dataset rather than a series of scripts.

Handling Mixed Expectations

Of course, real life is rarely that simple. Usually, you need to test both the "happy path" and the "failure path" in the same logic block, meaning you need both an input and an expected output. @ValueSource can't do that because it only takes one argument. For this, I usually reach for @CsvSource for simple cases, or @MethodSource when the data gets complex.

Here is how I'd handle the full suite of password tests in one go:

@ParameterizedTest
@CsvSource(
    "SafePass123!, true",
    "Short1!, false",
    "NoDigit!, false",
    "NoSpecial1, false",
    "'', false"
)
fun `password validation logic`(password: String, expected: Boolean) {
    assertEquals(expected, validator.isValid(password))
}

The trade-off here is a slight loss in "granularity" when reading the test report. Instead of seeing too short password should be invalid, you'll see password validation logic [1]. To fix that, you can add a custom name template to the annotation: @ParameterizedTest(name = "Password {0} should be valid: {1}"). I highly recommend doing this; otherwise, when a test fails in CI, you're left guessing which specific input caused the crash.

One final tip: if your test data requires complex objects (like a User entity) rather than just strings or booleans, @CsvSource will fail you. In those cases, use @MethodSource to point to a function that returns a Stream or a List of Arguments. It's a bit more verbose, but it keeps your test logic decoupled from your data generation.




📋 Practical Task

Refactoring the Discount Engine Test Suite

You have been handed a legacy test class for a DiscountEngine. The current developer wrote six separate test methods to verify that different customer types (GOLD, SILVER, BRONZE, GUEST) get the correct discount percentages based on their spend. It looks like a mess of repeated assertEquals calls.

Your Task:

  1. Create a DiscountEngine class with a method calculateDiscount(customerType: String, amount: Double): Double.
  2. Implement the following logic:
    • GOLD: 20% discount if spend > 100, otherwise 10%.
    • SILVER: 10% discount if spend > 100, otherwise 5%.
    • BRONZE: 5% discount regardless of spend.
    • GUEST: 0% discount.
  3. Write a single @ParameterizedTest using @CsvSource that replaces the need for individual test methods. Your test should verify at least five different scenarios (e.g., GOLD with 150, GOLD with 50, GUEST with 200, etc.).
  4. Add a custom name attribute to the @ParameterizedTest annotation so the test results clearly show the customer type and amount being tested.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.