Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Testing kotlin:如何从Spek类继承以拥有公共fixture_Testing_Kotlin_Spek - Fatal编程技术网

Testing kotlin:如何从Spek类继承以拥有公共fixture

Testing kotlin:如何从Spek类继承以拥有公共fixture,testing,kotlin,spek,Testing,Kotlin,Spek,我想为我的测试提供一个通用夹具: @RunWith(JUnitPlatform::class) abstract class BaseSpek: Spek({ beforeGroup {println("before")} afterGroup {println("after")} }) 现在我想使用这个规范: class MySpek: BaseSpek({ it("should xxx") {} }) 但是由于没有argBaseSpekconstructor,

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

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

    beforeGroup {println("before")}

    afterGroup {println("after")}
})
现在我想使用这个规范:

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

但是由于没有arg
BaseSpek
constructor,我得到了编译错误。实现我所需的正确方法是什么?

您可以在
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
s继承的工作选项:

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
的形式传递给父
BaseSpek
,这会将设置添加到它传递给
Spek

的内容中。你能在你的问题中发布完整的错误吗?更新了答案,添加了带有继承的工作选项。