简体   繁体   English

如何在 Kotlin 中使用 MethodSource 编写 Nested ParametrizedTest?

[英]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.我正在学习如何使用 JUnit 5 在 Kotlin 中编写测试。我喜欢在编写 ZD52387880E1EA22817A72D375 时使用@Nested@ParametrizedTest@MethodSource类的功能But when I switch to Kotlin, I encounter an issue:但是当我切换到 Kotlin 时,我遇到了一个问题:

I figured out how to use我想出了如何使用

But when I put this together, I got但是当我把它放在一起时,我得到了

Companion object is not allowed here.此处不允许使用伴侣 object。

inside the inner class.在内部 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?所以我可以一起使用@Nested@ParametrizedTest@MethodSource吗?

You can specify the method by using fully qualified name of the outer class @MethodSource("com.example.SolutionTest#testCases")您可以使用外部 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),
      )
    }
  }
}

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:如果您不介意使用@TestInstance(PER_CLASS) ,那么您可以像普通的 Kotlin 方法一样定义您的 MethodSource 方法,而无需伴随的 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()
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM