You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Kotlin中结合@Nested、@ParametrizedTest与@MethodSource编写测试?

解决JUnit 5 Kotlin测试中@Nested、@ParametrizedTest与@MethodSource结合的报错问题

你遇到的「Companion object is not allowed here」错误,本质是Kotlin的inner内部类不能包含companion object——inner类依赖外部类的实例,而companion object是类级别的静态成员,二者语法冲突。以下是两种可行的解决方法:

方法1:移除inner关键字,将嵌套类改为静态嵌套类

JUnit 5的@Nested注解并不要求嵌套类是inner类,只要是静态嵌套类就能正常识别。去掉inner后,即可在嵌套类中添加companion object:

internal class SolutionTest {
    @Nested
    class NestedTest { // 移除inner关键字
        @ParameterizedTest
        @MethodSource("testCases")
        fun given_input_should_return_expected(input: Int, expected: Int) {
            // 编写断言逻辑
        }

        companion object {
            @JvmStatic
            fun testCases(): List<Arguments> {
                return listOf(
                    Arguments.of(1, 2),
                    Arguments.of(3, 6)
                )
            }
        }
    }
}

方法2:保留inner类,将测试数据源移到外部类的companion object

如果嵌套类必须是inner类(比如需要访问外部类的实例成员),可以把testCases方法放到外部类的companion object中,再通过@MethodSource引用:

internal class SolutionTest {
    companion object {
        @JvmStatic
        fun testCases(): List<Arguments> {
            return listOf(
                Arguments.of(1, 2),
                Arguments.of(3, 6)
            )
        }
    }

    @Nested
    inner class NestedTest { // 保留inner关键字
        @ParameterizedTest
        @MethodSource("testCases") // 直接引用外部类的数据源方法
        fun given_input_should_return_expected(input: Int, expected: Int) {
            // 编写断言逻辑,可访问外部类实例成员
        }
    }
}

若存在同名方法,可通过全限定名明确指定:

@MethodSource("${SolutionTest::class.qualifiedName}#testCases")

内容的提问来源于stack exchange,提问作者samabcde

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:15:19