2014-10-29 66 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