2013-03-27 115 views
3

我有需要利用REST服務的一些夾具數據FlatSpec測試類。在一次運行所有測試時,我只想真正實例化REST客戶端,因爲它可能非常昂貴。我該如何去解決這個問題,當我在我的IDE中運行時,我還可以讓它運行一個測試類嗎?Scalatest共享服務實例

+1

我有同樣的問題與我的集成測試。你找到一個解決方案: – arpad 2015-06-25 06:48:55

回答

1

1.使用嘲諷:

我會建議你使用某種嘲諷當您嘗試測試REST服務。你可以嘗試例如scala-mock。模擬服務的創新是沒有時間/ CPU消耗,這樣你就可以創建所有的測試嘲笑,並不需要分享。 看:

trait MyRestService { 
    def get(): String 
} 

class MyOtherService(val myRestService: MyRestService) { 
    def addParentheses = s"""(${myRestService.getClass()})""" 
} 

import org.scalamock.scalatest.MockFactory 

class MySpec extends FreeSpec with MockFactory { 

    "test1 " in { 
    // create mock rest service and define it's behaviour 
    val myRestService = mock[MyRestService] 
    val myOtherService = new MyOtherService(myRestService) 
    inAnyOrder { 
     (myRestService.get _).expects().returning("ABC") 
    } 

    //now it's ready, you can use it 
    assert(myOtherService.addParentheses === "(ABC)") 
    } 
} 

2.或者使用共享夾具:

如果你還想要你REST服務使用真正的實施和創建只有一個實例,然後使用一些測試condider分享:

  • GET-固定方法=>當你需要在多次測試相同的可變夾具的對象,也不需要清理後使用它。

  • withFixture(OneArgTest)=>使用時,全部或大部分的測試需要,必須清理後記相同的燈具。

有關更多詳細信息和代碼示例,請參閱http://www.scalatest.org/user_guide/sharing_fixtures#loanFixtureMethods

如果你想對多個套房使用org.scalatest.Suites@DoNotDiscover註釋共享同一夾具(這些至少需要scalatest-2.0.RC1)

+0

謝謝,我會看看到夾具共享。這些是端到端的測試,我在單元測試中使用了模擬。 – shmish111 2013-10-09 19:48:21

0

帕維爾的最後的評論非常適合。 這是由繼承套房與BeforaAndAfterAll代替套房更容易。

import com.typesafe.config.ConfigFactory 
import com.google.inject.Guice 
import org.scalatest.{BeforeAndAfterAll, Suite} 
import net.codingwell.scalaguice.InjectorExtensions.ScalaInjector 

class EndToEndSuite extends Suite with BeforeAndAfterAll { 

    private val injector = { 
     val config = ConfigFactory.load 
     val module = new AppModule(config) // your module here 
     new ScalaInjector(Guice.createInjector(module)) 
    } 

    override def afterAll { 
     // your shutdown if needed 
    } 

    override val nestedSuites = collection.immutable.IndexedSeq(
     injector.instance[YourTest1], 
     injector.instance[YourTest2] //... 
    ) 
}