Kotlin
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Null Safety
-
Section 4: Object-Oriented Kotlin
-
Section 5: Functional Kotlin
-
Section 6: Coroutines
-
Section 7: Collections Deep Dive
-
Section 8: Type System Deep Dive
-
Section 9: Interop and Tooling
-
Section 10: Kotlin DSLs and Patterns
-
Section 11: Testing and Quality
-
Section 12: Server-Side Kotlin
-
Section 13: Practical Projects
-
Section 14: Interview Practice
-
Section 15: More Practice Exercises
-
Section 16: More Standard Library
-
Section 17: Multiplatform Kotlin
-
Section 18: kotlin.collections In Depth
-
Section 19: kotlin.text In Depth
-
Section 20: kotlin.ranges and kotlin.sequences
-
Section 21: kotlin.io and File Handling
-
Section 22: kotlinx.coroutines Deep Dive
-
Section 23: kotlin.reflect
-
Section 24: Android Development with Kotlin Overview
-
Section 25: Kotlin Multiplatform Deep Dive
-
Section 26: Kotlin for Backend Deep Dive
-
Section 27: Kotlin Design Patterns
-
Section 28: Advanced Language Features
-
Section 29: More Practice Exercises
-
Section 30: More Interview Practice
-
Section 31: Kotlin Type System Deep Dive
-
Section 32: Kotlin Null Safety Advanced
-
Section 33: Kotlin Testing Deep Dive
-
Section 34: Kotlin Build Tooling Deep Dive
-
Section 35: Kotlin Serialization
-
Section 36: Kotlin Performance Considerations
-
Section 37: Kotlin Native Overview
-
Section 38: Kotlin for Data and Scripting
-
Section 39: More Coroutines Practice
-
Section 40: More Android-Adjacent Patterns
-
Section 41: More Practical Projects
-
Section 42: More Design and Architecture Practice
-
Section 43: Kotlin Language Evolution
-
Section 44: More Interview and Review
-
Section 45: Kotlin Delegation Patterns Deep Dive
-
Section 46: Kotlin Annotations Deep Dive
-
Section 47: Kotlin for Gradle Plugin Development
-
Section 48: Kotlin Concurrency Beyond Coroutines
-
Section 49: Kotlin Compiler Internals
-
Section 50: Real-World Kotlin Case Studies
-
Section 51: Final Practice Projects
-
Section 52: Kotlin for Server-Side Reactive Programming
-
Section 53: More Practice and Drills
-
Section 54: Kotlin Security Practices
156: Parameterized Tests in Kotlin
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:
- Create a
DiscountEngineclass with a methodcalculateDiscount(customerType: String, amount: Double): Double. - 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.
- Write a single
@ParameterizedTestusing@CsvSourcethat 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.). - Add a custom
nameattribute to the@ParameterizedTestannotation so the test results clearly show the customer type and amount being tested.
There are no comments for now.