我正在学习如何使用 JUnit 5 在 Kotlin 中编写测试。在编写 Java 时,我喜欢使用
@Nested
、@ParametrizedTest
和 @MethodSource
等功能。但是当我切换到 Kotlin 时,我遇到了一个问题:
我知道如何使用了
@Nested
通过引用此运行 gradle 测试时未找到嵌套 Kotlin 类中的 JUnit 测试@ParametrizedTest
和 @MethodSource
,请参阅 JUnit 5 for Kotlin 开发人员 - 第 4.2 节但是当我把这些放在一起时,我得到了
此处不允许使用伴生对象。
在内部类中。
测试重现错误
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()
}
}
}
}
这个错误可以解决吗?那么我可以同时使用
@Nested
、@ParametrizedTest
和 @MethodSource
吗?
您可以使用外部类的完全限定名称来指定方法
@MethodSource("com.example.SolutionTest#testCases")
这是一个嵌套测试示例。
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),
)
}
}
}
如果您不介意拥有
@TestInstance(PER_CLASS)
,那么您可以像普通的 Kotlin 方法一样定义 MethodSource 方法,而不需要伴随对象:
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()
}
}
}
在内部类中拥有常量是不可能的,请参阅https://discuss.kotlinlang.org/t/how-do-i-define-constants-in-an-inner-class/14260
如果接受的答案不适合您的情况,并且您仍然希望实现某种形式的将事物分组在一起,您可以让您的父类有一个伴生对象,并为单独的嵌套类提供单独的对象
class TestParent {
@Nested
inner class NestedTest1 {
@ParameterizedTest
@MethodSource("FULLY.QUALIFIED.NAME.TO.TestParent.Companion.NestedConstants1#testCases")
fun testNested() {
}
}
@Nested
inner class NestedTest2 {
@ParameterizedTest
@MethodSource("FULLY.QUALIFIED.NAME.TO.TestParent.Companion.NestedConstants2#testCases")
fun testNested() {
}
}
companion object {
object NestedConstants1 {
@JvmStatic
fun testCases(): List<Arguments> {
return emptyList()
}
}
object NestedConstants2 {
@JvmStatic
fun testCases(): List<Arguments> {
return emptyList()
}
}
}
}