2017-09-09 65 views
0

我想用Kotlin + Spek框架編寫單元測試。到目前爲止看起來相當不錯,但我有一個問題,我必須編寫大量的樣板代碼,如果我想要測試一個類的幾個Spec對象。用Kotlin和Spek創建一個用於初始化共享對象的抽象Spek

這是我的代碼來說明這個問題:

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

我很想創造「抽象」斯貝克,在那裏我將定義我的嘲笑等,並繼承後或在我的規格在某種程度上分享。

有沒有辦法做到這一點?

回答

0

不幸的是,我沒有找到抽象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 
     } 
    } 
}) 

希望這將是一個人,誰有同樣的問題

有用