2014-10-29 63 views
1

我有兩個模擬對象,我用它來創建一個Guice測試模塊。 我有兩個問題:Play測試中的依賴注入Scala應用s

  1. 我需要每次測試之前創建的模擬對象,如果我驗證模擬的互動呢?我想是的,爲了實現它,我想我需要使用「之前」的塊。

  2. 如何創建以下DRY原則的每個測試吉斯測試模塊:)(即如何使用同一個代碼塊的每個測試)

這是代碼我有這麼遠

class SampleServiceTest extends Specification with Mockito with BeforeExample { 

     //Mock clients 
     var mockSample: SampleClient = null //this ugly but what is the right way? 
     var mockRedis: RedisClient = null 

     def before = { 
     println("BEFORE EXECUTED") 
     mockSample = mock[SampleClient] 
     mockRedis = mock[RedisClient] 
     } 

     def after = { 
     //there were noMoreCallsTo(mockRedis) 
     //there were noMoreCallsTo(mockSample) 
     } 

     object GuiceTestModule extends AbstractModule { //Where should I create this module 
     override def configure = { 
      println(" IN GUICE TEST") 
      bind(classOf[Cache]).toInstance(mockRedis) 
      bind(classOf[SampleTrait]).toInstance(mockSample) 
     } 
     } 

     "Sample service" should { 
     "fetch samples from redis should retrieve data" in { 
     running(FakeApplication()) { 
      println("TEST1") 
      val injector = Guice.createInjector(GuiceTestModule) 
      val client = injector.getInstance(classOf[SampleService]) 
      mockRedis.get("SAMPLES").returns(Some(SampleData.redisData.toString)) 
      val result = client.fetchSamples 
      there was one(mockRedis).get("SAMPLES") //verify interactions 
      Json.toJson(result) must beEqualTo(SampleData.redisData) 
     } 
     } 
    } 
    } 

回答

2
  1. 您可以使用org.specs2.specification.Scope

像這樣:

trait TestSetup extends Scope { 
    val mockSample = mock[SampleClient] 
    val mockRedis = mock[RedisClient] 

    object GuiceTestModule extends AbstractModule { 
    override def configure = { 
     println(" IN GUICE TEST") 
     bind(classOf[Cache]).toInstance(mockRedis) 
     bind(classOf[SampleTrait]).toInstance(mockSample) 
    } 
    } 
} 

,然後用在每個測試用例

"something with the somtehing" in new TestSetup { 
    // you can use the mocks here with no chance that they 
    // leak inbetween tests 
} 

我想你也有去注射到你的播放應用,使控制器等將實際使用你的嘲笑對象,沒有使用Guice玩,所以我不知道該怎麼做。

+0

你的建議絕對有意義。 Howevef當我這樣做時,我的交互驗證停止工作。例如'沒有(mockRedis).get(「SAMPLES」)'也通過了,但它會失敗?你有什麼想法爲什麼 – Richeek 2014-10-29 16:40:14

+0

我想你需要告訴你的遊戲應用使用你的模擬Guice模塊,但我不知道該怎麼做,我害怕。也許這可以幫助(特別是他們如何在dev和prod中使用不同的模塊):http://eng.kifi.com/play-framework-dependency-injection-guice/ – johanandren 2014-10-30 08:55:10

+0

以及我使用'isolated'參數工作。回答你的問題:在我的情況下,我不需要告訴我的應用程序使用Guice,因爲我沒有啓動應用程序只是運行單元測試。我使用'val injector = Guice.createInjector(GuiceTestModule)'創建了噴油器 – Richeek 2014-10-30 20:51:40