0

我正在尝试使用 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
    }
})

我很想创建“抽象”Spek,我将在其中定义我的模拟等,然后在我的 Specs 中以某种方式继承或共享它。

有没有办法做到这一点?

4

1 回答 1

1

不幸的是,我没有找到制作 Abstract 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
        }
    }
})

希望对遇到同样问题的人有用

于 2017-09-09T17:49:32.810 回答