我的Play应用程序的构造函数接受了一个参数,如何在Spec Test中给出一个模拟参数?

时间:2016-12-15 18:14:57

标签: scala playframework dependency-injection mocking specs2

如果我的播放应用程序有这样的内容:

class Foo() extends Bar {} 

class Application @Inject (f: Foo) extends Controller {
  def index = Action { OK("Hi, Foo App") }
}

如何更改我的规范测试以接受MockedFoo类?

@RunWith(classOf[JUnitRunner])

class MockedFoo() extends Bar {}

class ApplicationTest(implicit ee: ExecutionEnv) extends Specification  {

  "Sending a GET request to index " should {

    "Respond with OK " in new WithApplication { //######## Inject MockedFoo
      val response = route(app, FakeRequest(GET, "/")).get
      status(response) mustEqual OK
    }
  }
}

感谢您的帮助:

1 个答案:

答案 0 :(得分:0)

从我自己的要点复制:https://gist.github.com/rethab/01fde763d10f29273d43

首先,为方便起见创建一个帮助类:

class WithFancyApp(lang: Lang = Lang.defaultLang,
                   overrideModules: Seq[GuiceableModule] = Seq()) extends
  WithApplication(
    app =
      new GuiceApplicationBuilder()
      .in(Environment(new File("."), getClass.getClassLoader, Mode.Test))
      .loadConfig(env => Configuration.load(env))
      .overrides(overrideModules:_*)
      .bindings()
      .build
 ) {

  implicit def messages: Messages = Messages(lang, app.injector.instanceOf[MessagesApi])

}

用法:

"use the overridden bindigs" in new WithFancyApp(
       overrideModules = Seq(bind[MyInterface].to[MyImplementation])
) {
    // test stuff with all regular bindings plus the ones from above
}