Search code examples
kotlinjunit4junit5

How to combine JUnit4 @RunWith(Parameterized.class) and JUnit5 @ParameterizedTest


I am trying to combine the concept of a Parameterized runner from JUnit4 with the JUnit5 Parameterized Test. Essentially I want to test two separate functions on the same set of data.

I know I could just add the function as another argument to the parameterized test itself but I am trying to make changing or adding new functions to test easy.

Would I be able to leverage nested test classes to achieve this? I am not sure the best way to approach.

@RunWith(Parameterized::class)
class RomanNumeralTest(val func: (Int) -> String) {

    @ParameterizedTest(name = "{index} - Expect [{0}] should return [{1}]")
    @MethodSource("testData")
    fun `Test roman numeral from integer values`(num: Int, expected: String) =
            assertEquals(expected, func(num))

    companion object {

        @JvmStatic
        @Parameterized.Parameters
        fun data(): Collection<Array<(Int) -> String>> {
            return listOf(
                    arrayOf({num -> roman(num)}),
                    arrayOf({num -> num.toRomanNumeral()})
            )
        }

        @JvmStatic
        private fun testData() = sequenceOf(
                arrayOf(1, "I"),
                arrayOf(2, "II"),
                arrayOf(3, "III"),
                arrayOf(4, "IV"),
                arrayOf(5, "V")
        ).asStream()
    }
}

Solution

  • I tried the same but in the end I came to the conclusion that: you can't.

    There is no way you can use the JUnit 4 Parameterized test runner using the annotations which came with JUnit 5.

    You need to move to JUnit 5 to use the latest features like TestFactory or all the powerful annotations of parameterized tests described here