Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  • @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?

like image 279
samabcde Avatar asked Apr 17 '26 04:04

samabcde


1 Answers

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),
      )
    }
  }
}
like image 78
ocos Avatar answered Apr 19 '26 11:04

ocos