Parameterized JUnit4 Unit Tests in Kotlin

This weekend I’ve been learning a little Kotlin — the (relatively) new JVM language from JetBrains. Once I’d worked my through the “Koans”, I decided to try a simple Code Kata. I chose the Roman Numerals Kata for this exercise. Whilst doing this, I wanted to use a parameterised unit test, and had to figure out how to do that in Kotlin… I wont go into the details of the Kata (read the link if you are interested), but in a nutshell, the goal is to write a program that will convert the Arabic numerals we are accustomed to in the modern world to the representation used by the ancient Romans. For example, you may have noticed Roman Numerals used to denote the year a movie was released: 1977 becomes “MCMLXXVII”.

As I set out on the exercise using TDD, I got to the point where I had two similar unit tests:

At this point we can see that there is some duplication in the tests. The rest of the tests will follow a similar pattern. Therefore, I wanted to refactor the tests to become parameterised tests — this is what I’d usually do when writing a Java JUnit4 test, after all. In Java, this involves:

indicating that the Parameterized test runner should be used

adding a static method — denoted by the @Parameters annotation — that that will provide the collection of test cases containing an array of parameters for each test

add a constructor to the test class that will receive the parameters for each test case

It may look a little like this:

(obviously, we’d use better variable names than paramOne and paramTwo when doing this for real, I’ve used these here for clarity)