我的Play应用程序的构造函数接受一个参数,如何在Spec Test中给出一个模拟的参数? [英] My Play Application's Constructor takes an argument, how do I give a mocked argument at Spec Test?

查看:50
本文介绍了我的Play应用程序的构造函数接受一个参数,如何在Spec Test中给出一个模拟的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的播放应用程序具有以下内容:

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") }
}

如何更改规格测试以接受MockedFoo类?

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

感谢您的帮助:

推荐答案

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

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

}

用法:

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

这篇关于我的Play应用程序的构造函数接受一个参数,如何在Spec Test中给出一个模拟的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆