sam*_*cde 8 kotlin junit5 parametrized-testing
我正在学习如何使用 JUnit 5 在 Kotlin 中编写测试。当我编写 Java 时@Nested,我喜欢使用 、@ParametrizedTest等功能。@MethodSource但是当我切换到 Kotlin 时,我遇到了一个问题:
我想出了如何使用
@Nested通过在运行 gradle 测试时未找到嵌套 Kotlin 类中引用此JUnit 测试@ParametrizedTest并@MethodSource参考适用于 Kotlin 开发人员的 JUnit 5 - 第 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()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
有可能解决这个错误吗?那么我可以一起使用@Nested,@ParametrizedTest和吗?@MethodSource
oco*_*cos 10
您可以使用外部类的完全限定名称来指定方法
@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),
)
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您不介意拥有@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()
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1736 次 |
| 最近记录: |