gpt4 book ai didi

testing - kotlin:如何从 Spek 类继承以拥有公共(public)夹具

转载 作者:行者123 更新时间:2023-11-28 20:07:57 26 4
gpt4 key购买 nike

我想为我的测试使用一个通用的夹具:

@RunWith(JUnitPlatform::class)
abstract class BaseSpek: Spek({

beforeGroup {println("before")}

afterGroup {println("after")}
})

现在我想使用那个规范:

class MySpek: BaseSpek({
it("should xxx") {}
})

但是由于无参数 BaseSpek 构造函数,我得到了编译错误。什么是实现我需要的正确方法?

最佳答案

您可以在 Spec 上定义一个扩展来设置所需的夹具,然后将其应用到您的 Spek 中,如下所示:

fun Spec.setUpFixture() {
beforeEachTest { println("before") }
afterEachTest { println("after") }
}

@RunWith(JUnitPlatform::class)
class MySpek : Spek({
setUpFixture()
it("should xxx") { println("xxx") }
})

虽然这不是您所要求的,但它仍然允许灵活的代码重用。


UPD:这是 Spek 继承的工作选项:

open class BaseSpek(spec: Spec.() -> Unit) : Spek({
beforeEachTest { println("before") }
afterEachTest { println("after") }
spec()
})

@RunWith(JUnitPlatform::class)
class MySpek : BaseSpek({
it("should xxx") { println("xxx") }
})

基本上,做这个,你反转继承方向,这样子 MySpek 将它的设置以 Spec.() -> Unit 的形式传递给parent BaseSpek,它将设置添加到它传递给 Spek 的内容中。

关于testing - kotlin:如何从 Spek 类继承以拥有公共(public)夹具,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49008999/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com