如何使用Kotest和AnnotationSpec样式创建带参数的测试。

huangapple go评论72阅读模式
英文:

How create parameterized tests with kotest and AnnotationSpec style

问题

如何在Kotest中使用数据驱动的*AnnotationSpec()*样式

JUnit 5的示例:

@ParameterizedTest
@ValueSource(ints = {1, 3, 5, -3, 15, Integer.MAX_VALUE}) // 六个数字
fun isOdd_ShouldReturnTrueForOddNumbers(number: Int) {
    assertTrue(Numbers.isOdd(number))
}

在Kotest中如何实现这个?这是我尝试的方式:

class AnnotationSpecExample : AnnotationSpec() {

    @Test
    fun test1(value: Int) {
        value shouldBe 1
    }
}

我找不到文档和示例。

英文:

How to use data driven in Kotest with style AnnotationSpec()

Example for JUnit 5:

@ParameterizedTest
@ValueSource(ints = {1, 3, 5, -3, 15, Integer.MAX_VALUE}) // six numbers
void isOdd_ShouldReturnTrueForOddNumbers(int number) {
    assertTrue(Numbers.isOdd(number));
}

How can I do this in Kotest? This is what I tried to come up with:

class AnnotationSpecExample : AnnotationSpec() {

    @Test
    fun test1(value: Int) {
        value shouldBe 1
    }
}

I couldn't find documentation and examples.

答案1

得分: 1

The Annotation spec style is an easy way to migrate your JUnit tests to Kotest, but it doesn't have much to offer and I suggest that you use another more "Kotest-idiomatic" style instead, like FunSpec.

The counterpart of parameterized tests in Kotest would be data driven testing in Kotest. In a FunSpec test, your example looks like this, using withData from the kotest-framework-datatest module:

class OddNumberTest : FunSpec({
    context("odd numbers") {
        withData(1, 3, 5, -3, 15, Integer.MAX_VALUE) { number ->
            number should beOdd()
        }
    }
})

The problem when you try to use Annotation Spec style here, is that you cannot use withData in a leaf scope, but only in root or container scopes, and each test in an Annotation spec is a leaf.

英文:

The Annotation spec style is an easy way to migrate your JUnit tests to Kotest, but it doesn't have much to offer and I suggest that you use another more "Kotest-idiomatic" style instead, like FunSpec.

The counterpart of parameterized tests in Kotest would be data driven testing in Kotest. In a FunSpec test, your example looks like this, using withData from the kotest-framework-datatest module:

class OddNumberTest : FunSpec({
    context("odd numbers") {
        withData(1, 3, 5, -3, 15, Integer.MAX_VALUE) { number ->
            number should beOdd()
        }
    }
})

The problem when you try to use Annotation Spec style here, is that you cannot use withData in a leaf scope, but only in root or container scopes, and each test in an Annotation spec is a leaf.

huangapple
  • 本文由 发表于 2023年7月18日 15:53:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76710593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定