kotlinjunit5parametrized-testing

How to write Nested ParametrizedTest with MethodSource in Kotlin?


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

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?


Solution

  • 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()
            }
        }
    }