Parameterized tests

suggest change

Parameterized tests execute the same test logic repeatedly with different sets of inputs and assertions. They eliminate duplicate test methods while systematically testing boundary values, edge cases, and regression datasets.

In Kotlin, parameterized testing is provided by JUnit 5 Jupiter Params.


Adding the Dependency

Add junit-jupiter-params to your build.gradle.kts:

dependencies {
    testImplementation("org.junit.jupiter:junit-jupiter-api:5.14.4")
    testImplementation("org.junit.jupiter:junit-jupiter-params:5.14.4")
    testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.14.4")
}

tasks.test {
    useJUnitPlatform()
}

Simple Value Inputs with @ValueSource

@ValueSource supplies a literal array of primitive values or strings:

import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.ValueSource
import kotlin.test.assertTrue
import kotlin.test.assertFalse

class ValidationTest {

    fun isValidUsername(username: String): Boolean {
        return username.matches(Regex("^[a-zA-Z0-9_]{3,16}$"))
    }

    @ParameterizedTest
    @ValueSource(strings = ["alice", "bob_123", "admin_user", "DEV"])
    fun `valid usernames should be accepted`(username: String) {
        assertTrue(isValidUsername(username))
    }

    @ParameterizedTest
    @ValueSource(strings = ["", "ab", "user with spaces", "user@domain", "this_username_is_way_too_long_to_be_valid"])
    fun `invalid usernames should be rejected`(username: String) {
        assertFalse(isValidUsername(username))
    }
}

Multi-Argument Tests with @CsvSource

@CsvSource accepts comma-separated values, mapping each row to multiple method parameters:

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

class CalculatorTest {

    fun add(a: Int, b: Int): Int = a + b

    @ParameterizedTest(name = "Test {index}: {0} + {1} should equal {2}")
    @CsvSource(
        "1, 2, 3",
        "0, 0, 0",
        "-5, 10, 5",
        "100, -200, -100"
    )
    fun `addition of numbers yields expected sum`(a: Int, b: Int, expected: Int) {
        assertEquals(expected, add(a, b))
    }
}

For large datasets, use @CsvFileSource(resources = "/test-data.csv", numLinesToSkip = 1).


Complex Arguments with @MethodSource

When testing complex domain models or collections, @MethodSource references a function that returns a Stream, Iterable, or Sequence of arguments.

In standard JUnit 5, @MethodSource targets must be static. In Kotlin, annotating the test class with @TestInstance(TestInstance.Lifecycle.PER_CLASS) allows clean, top-level non-static member functions without verbose companion object and @JvmStatic boilerplate:

import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream
import kotlin.test.assertEquals

data class DiscountCase(val membershipTier: String, val cartTotal: Double, val expectedDiscount: Double)

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class DiscountCalculatorTest {

    fun calculateDiscount(tier: String, total: Double): Double = when (tier) {
        "VIP" -> total * 0.20
        "GOLD" -> total * 0.10
        else -> 0.0
    }

    fun discountTestCases(): Stream<Arguments> = Stream.of(
        Arguments.of(DiscountCase("VIP", 100.0, 20.0)),
        Arguments.of(DiscountCase("VIP", 50.0, 10.0)),
        Arguments.of(DiscountCase("GOLD", 100.0, 10.0)),
        Arguments.of(DiscountCase("STANDARD", 100.0, 0.0))
    )

    @ParameterizedTest
    @MethodSource("discountTestCases")
    fun `discounts apply correctly per tier`(testCase: DiscountCase) {
        val actual = calculateDiscount(testCase.membershipTier, testCase.cartTotal)
        assertEquals(testCase.expectedDiscount, actual, 0.001)
    }
}

Testing Enums with @EnumSource

@EnumSource tests all or selected constants of an enum class:

import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.EnumSource
import kotlin.test.assertTrue

enum class UserRole { GUEST, VIEWER, EDITOR, ADMIN }

class AuthorizationTest {

    fun hasEditPermissions(role: UserRole): Boolean = role in setOf(UserRole.EDITOR, UserRole.ADMIN)

    @ParameterizedTest
    @EnumSource(value = UserRole::class, names = ["EDITOR", "ADMIN"])
    fun `editors and admins have edit permissions`(role: UserRole) {
        assertTrue(hasEditPermissions(role))
    }
}

Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents