Parameterized Tests in Kotlin With Junit5
Recently I’ve worked on a few projects that have made use of interfaces in critical sections of code, with the goal of adding several more in the near future. One of these projects is tlp-stress, a load testing tool we’ve created at The Last Pickle in an attempt to make benchmarking Cassandra easier.
JUnit has a great feature called parameterized tests. You can define a collection of objects that will be passed as arguments to a test, and the test will be run once for each iteration in the list. This lets you clearly see which tests passed and which failed in your IDE or test output, and is great because we can write a suite of unit tests against an interface and run a comprehensive set of tests against every implementation of that interface. In this post I’ll show you how to leverage parameterized tests in Kotlin.
First, you’ll need the Junit 5 dependency:
testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: '5.4.0'
Next, we need to define an annotation that we’ll use on any tests
@Retention(AnnotationRetention.RUNTIME)
@MethodSource("getPlugins")
annotation class AllPlugins
Next we create a compantion object which must be annotated with @JvmStatic
that returns a collection.
class AllPluginsBasicTest {
companion object {
@JvmStatic
fun getPlugins() = Plugin.getPlugins().values
}
}
@AllPlugins
@ParameterizedTest(name = "ensure it works {0}")
fun runEachTest(plugin: Plugin) {
val run = Run()
run.apply {
profile = plugin.name
}.execute()
}