描述子句中的kotest嵌套规范

我已经开始使用kotest:4.0.5(kotlintest),并且对嵌套在stringSpec子句中的describe函数有疑问。

示例:

class SellerTest : DescribeSpec({

    describe("Registration") {
        context("Not existing user") {
            include(emailValidation()
        }
    }
})

fun emailValidation() = stringSpec {
    "Email validation" {
        forAll(
            row("test.com"),row("123123123123123")
        ) { email ->
            assertsoftly {
                val exception =
                    shouldThrow<ServiceException> { Email(email) }

            }
        }
    }
}

如果include(emailValidation())describe子句之外,则可以正常工作。

您知道如何在子句中嵌套规范/功能吗?

iCMS 回答:描述子句中的kotest嵌套规范

您只能在顶层使用include。这是工厂测试(使用include关键字的用途)的实现方式的一部分(也许在将来的版本中会放宽)。

但是您可以将整个东西搬到工厂。

class SellerTest : DescribeSpec({
  include(emailValidation)
})

val emailValidation = describeSpec {

    describe("Registration") {
        context("Not existing user") {
            forAll(
                row("test.com"),row("123123123123123")
            ) { email ->
                assertSoftly {
                    val exception =
                        shouldThrow<ServiceException> { Email(email) }
                }
            }
        }
    }
}

您可以参数化所有所需的命名,因为这只是字符串,例如:

fun emailValidation(name: String) = describeSpec {
    describe("Registration") {
        context("$name") {
        }
    }
}

如果您不进行参数设置,那么拥有测试工厂将毫无意义。只需声明测试内联IMO。

,

对于嵌套的 include,您可以实现自己的工厂方法,如下例所示:

class FactorySpec : FreeSpec() {
    init {
        "Scenario: root container" - {
            containerTemplate()
        }
    }
}

/** Add [TestType.Container] by scope function extension */
suspend inline fun FreeScope.containerTemplate(): Unit {
    "template container with FreeScope context" - {
        testCaseTemplate()
    }
}

/** Add [TestType.Test] by scope function extension */
suspend inline fun FreeScope.testCaseTemplate(): Unit {
    "nested template testcase with FreeScope context" { }
}

注意传递给ScopecontainerTemplate的扩展函数的testCaseTemplate

输出:

Scenario: root container
   template container with FreeScope context
       nested template testcase with FreeScope context
本文链接:https://www.f2er.com/2262848.html

大家都在问