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.2
But 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?
CodePudding user response:
You can specify the method by using fully qualified name of the outer class
@MethodSource("com.example.SolutionTest#testCases")
Here is an example nested test.
package com.example
// imports
internal class SolutionTest {
@Test
fun outerTest() {
// ...
}
@Nested
inner class NestedTest {
@ParameterizedTest
@MethodSource("com.example.SolutionTest#testCases")
fun given_input_should_return_expected(input: Int, expected: Int) {
Assertions.assertEquals(input 2, expected)
}
}
companion object {
@JvmStatic
fun testCases(): List<Arguments> {
return listOf(
Arguments.of(1, 3),
Arguments.of(2, 4),
)
}
}
}
CodePudding user response:
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()
}
}
}