Search code examples
kotlinspek

Testing with spek and sharing some base test-cases for base-classes


I'm using Spek as test framework, and have troubles when sharing some test-steps for base classes.

I have an abstract base class and two derived classes.

abstract class Base {
    abstract fun send()
}
class Foo : Base() {
    override fun send() {}
    fun anotherFunction() { }
}
class Bar : Base() {
    override fun send() {}
    fun differentFunction() { }
}

Now my question is: How can I create Speks for those classed, but only define the test for send() once in a base spek?

My first approach was to use SubjectSpek

class BaseSpek : SubjectSpek<Base>({
    subject {
        // ??? Can't instantiate Base because it is abstract
    }

    it("test the base") { ... }
})
class FooSpek : SubjectSpek<Foo>({
    itBehavesLike(BaseSpek)

    it("test anotherFunction") { ... }
})

My second approach was to use inheritance:

abstract class BaseSpek(base: Base) : Spek({
    it("test the base") { ... }
})
abstract class FooSpek() : BaseSpek(???)

It seems that none of my approaches works. Any suggestions how to solve this? Should I bring this to the attention of the Spek-Author for possible changes in future releases of Spek?


Solution

  • SubjectSpek is the correct approach.

    abstract class BaseSpec: SubjectSpek<Base>({
        it("test base") { ... }
    })
    
    object FooSpec: BaseSpec<Foo>({
        subject { ... }
    
        // ugly for now, until Spek supports @Ignore
        itBehavesLike(object: BaseSpec() {})
    
        it("test another") { ... }
    })