创建一个抽象Spek,用于使用Kotlin和Spek初始化共享对象

时间:2017-09-09 00:33:56

标签: unit-testing kotlin spek

我试图用Kotlin + Spek框架编写单元测试。到目前为止看起来还不错,但我有一个问题,我必须编写大量的样板代码,如果我想为一个类我有几个Spec对象进行测试。

这是我的代码来说明问题:

object MyFirstSpec : Spek({
    val myMock1: SomeObject1 = mock()
    val myMock2: SomeObject2 = mock()
    val myMock3: SomeObject3 = mock()
    val myMock4: SomeObject4 = mock()
    val myMock5: SomeObject5 = mock()
    val myMock6: SomeObject6 = mock()

    val myClass = MyClassToTest(myMock1, myMock2, myMock3, myMock4, myMock5, myMock6)

    given("something to test here") {
        //my test here
    }
})

object MyOtherSpec : Spek({
    val myMock1: SomeObject1 = mock()
    val myMock2: SomeObject2 = mock()
    val myMock3: SomeObject3 = mock()
    val myMock4: SomeObject4 = mock()
    val myMock5: SomeObject5 = mock()
    val myMock6: SomeObject6 = mock()

    val myClass = MyClassToTest(myMock1, myMock2, myMock3, myMock4, myMock5, myMock6)

    given("something else to test here") {
        //  my test here
    }
})

我很乐意创作“抽象”#39; Spek,在那里我将定义我的模拟等,然后在我的规范中以某种方式继承或分享它。

有没有办法实现这个目标?

1 个答案:

答案 0 :(得分:1)

不幸的是,我没有找到制作抽象Spek或继承的方法,但我找到了使用Fixtures来达到预期效果的方法。

这是我的伪代码演示:

object MySpec: Spek({
    describe("my tests with Fixtures") {
        val myMock1: SomeObject1 = mock()
        val myMock2: SomeObject2 = mock()
        val myMock3: SomeObject3 = mock()
        val myMock4: SomeObject4 = mock()
        val myMock5: SomeObject5 = mock()
        val myMock6: SomeObject6 = mock()

        val myClass = MyClassToTest(myMock1, myMock2, myMock3, myMock4, myMock5, myMock6)

        afterEachTest { 
            reset(myMock1, myMock2, myMock3, myMock4, myMock5, myMock6)
            //or we can just clear invocations, if we don't want to reset the mocks
            //clearInvocations(myMock1, myMock2, myMock3, myMock4, myMock5, myMock6)
        }

        context("my first context for testing") {
            //initialization logic here specific for this context
            val somethingSpecificHere = MySpecificLogicObject()
            beforeEachTest { 
                whenever(myMock1.doSomething()).thenReturn(someResult)
            }
            on ("calling the method i'm testing"){
                myClass.myMethod(somethingSpecificHere)

                it ("should do what expected") {
                    //verifies go here
                }
            }
        }
        context("my seconds context for testing") {
            //second context specific code
        }
    }
})

希望它对有同样问题的人有用