Play Scala应用程序测试中的依赖注入



我有两个mock对象,用于创建Guice测试模块。我有两个问题:

  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)
         }
       }
     }
   }
  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,所以我不知道该怎么做。

相关内容

  • 没有找到相关文章

最新更新