Parameterized JUnit4 Unit Tests in Kotlin
Posted on Saturday, 20th February 2016
(Jump to the TL;DR of how to create a Parameterized JUnit4 test 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)
Creating a parameterised test in Kotlin is a little different than in Java. The main reason being that Kotlin does not have static member functions on classes. However, we can add compatibility for calling Java code, by putting our function in a “companion object”, and annotating it with the @JvmStatic
annotation (Kotlin Reference).
For example:
Therefore, we can create a parameterised Kotlin unit test like so:
If you are interested in seeing this in action, you can check out my completed Roman Numerals Kata in Kotlin on Github: https://github.com/rossharper/RomanNumerals-Kotlin
git clone https://github.com/rossharper/RomanNumerals-Kotlin.git
TL;DR
To create a parameterised unit test in Kotlin:
- annotate the Kotlin test class with
@RunWith(Parameterized::class)
- place the
@Parameterized.Parameters
function within acompanion object
in the test class - annotate the
@Parameterized.@Parameters
function with the@JvmStatic
annotation — as Kotlin doesn’t have static functions, this allows Java code to call this Kotlin as if it were a static - Use Kotlin’s
Any
in place of Java’sObject