【发布时间】:2014-10-29 06:51:15
【问题描述】:
我有两个用于创建 Guice 测试模块的模拟对象。 我有两个问题:
如果我还要验证模拟交互,是否需要在每次测试之前创建模拟对象?我认为是的,为了实现它,我认为我需要使用“之前”块。
如何按照 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)
}
}
}
}
【问题讨论】:
标签: scala playframework mockito guice specs2