I'm learning how to write test in Kotlin with JUnit 5. I like using feature like @Nested
, @ParametrizedTest
and @MethodSource
when I was writing Java. But when I switch to Kotlin, I encounter an issue:
I figured out how to use
@Nested
by referring this JUnit test in nested Kotlin class not found when running gradle test@ParametrizedTest
and @MethodSource
by referring JUnit 5 for Kotlin Developers - section 4.2But when I put this together, I got
Companion object is not allowed here.
inside the inner class.
Test to reproduce the error
internal class SolutionTest {
@Nested
inner class NestedTest {
@ParameterizedTest
@MethodSource("testCases")
fun given_input_should_return_expected(input: Int, expected: Int) {
// assert
}
// error in below line
companion object {
@JvmStatic
fun testCases(): List<Arguments> {
return emptyList()
}
}
}
}
Is it possible to solve this error? So I can use @Nested
, @ParametrizedTest
and @MethodSource
together?
If you don't mind having @TestInstance(PER_CLASS)
, you can then define your MethodSource method just like a normal Kotlin method, without needing a companion object:
internal class SolutionTest {
@Nested
@TestInstance(PER_CLASS)
inner class NestedTest {
@ParameterizedTest
@MethodSource("testCases")
fun given_input_should_return_expected(input: Int, expected: Int) {
// assert
}
fun testCases(): List<Arguments> {
return emptyList()
}
}
}