我有两个模拟对象,用于创建Guice测试模块。 我有两个问题:
如果我还在验证模拟交互,我是否需要在每次测试之前创建模拟对象?我想是的,为了达到目的,我想我需要在#34;之前使用"块。
如何为DRY原则后的每个测试创建一个guice测试模块:)(即如何为每个测试使用相同的代码块)
这是我迄今为止的代码
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)
}
}
}
}
答案 0 :(得分:3)
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玩游戏所以我不知道该怎么做。