Search code examples
testingkotlinspek

kotlin: how to inherit from Spek class to have common fixture


I want to have a common fixture for my tests:

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

    beforeGroup {println("before")}

    afterGroup {println("after")}
})

and now I want to use that spec:

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

but i got compilation error due to no-arg BaseSpek constructor. what's the correct way of achieving what i need?


Solution

  • You can define an extension on Spec that sets up the desired fixture and then apply it in your Speks as follows:

    fun Spec.setUpFixture() {
        beforeEachTest { println("before") }
        afterEachTest { println("after") }
    }
    
    @RunWith(JUnitPlatform::class)
    class MySpek : Spek({
        setUpFixture()
        it("should xxx") { println("xxx") }
    })
    

    Though this is not exactly what you asked, it still allows flexible code reuse.


    UPD: This is a working option with Speks inheritance:

    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") }
    })
    

    Basically, do do this, you invert the inheritance direction, so that the child MySpek passes its setup in the form of Spec.() -> Unit to the parent BaseSpek, which adds the setup to what it passes to Spek.