kotlin:如何从 Spek 类继承以拥有通用固定装置

pio*_*rek 4 testing kotlin spek

我想要一个通用的测试装置:

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

    beforeGroup {println("before")}

    afterGroup {println("after")}
})
Run Code Online (Sandbox Code Playgroud)

现在我想使用该规范:

class MySpek: BaseSpek({
    it("should xxx") {}
})
Run Code Online (Sandbox Code Playgroud)

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

hot*_*key 5

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

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

@RunWith(JUnitPlatform::class)
class MySpek : Spek({
    setUpFixture()
    it("should xxx") { println("xxx") }
})
Run Code Online (Sandbox Code Playgroud)

尽管这并不完全符合您的要求,但它仍然允许灵活的代码重用。


UPD:这是一个具有 s 继承的工作选项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") }
})
Run Code Online (Sandbox Code Playgroud)

基本上,执行此操作,反转继承方向,以便子级MySpek将其设置以 的形式传递Spec.() -> Unit给父级BaseSpek,父级将设置添加到它传递给的内容中Spek