My Play Application's Constructor takes an argument, how do I give a mocked argument at Spec Test?

☆樱花仙子☆ 提交于 2019-12-23 05:11:09

问题


If my play application has something like this:

class Foo() extends Bar {} 

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

How do I change my spec test to accept MockedFoo class?

@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
    }
  }
}

Thanks for the help:


回答1:


Copying from my own Gist: https://gist.github.com/rethab/01fde763d10f29273d43

First, create a helper class for convenience:

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])

}

Usage:

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


来源:https://stackoverflow.com/questions/41170769/my-play-applications-constructor-takes-an-argument-how-do-i-give-a-mocked-argu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!