My Play Application's Constructor takes an arg

2019-06-14 08:05发布

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条回答
劳资没心,怎么记你
2楼-- · 2019-06-14 08:27

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
}
查看更多
登录 后发表回答