scala - 如何使用 ScalaTest 在 Playframework 单元测试中覆盖 guice 模块

标签 scala unit-testing playframework guice scalatest

我想在 PlayFramework 中为我的 Controller 编写功能测试。为此,我想模拟一些类的实现。

我在这里找到了如何使用 spec2 来做到这一点的好例子:http://www.innovaedge.com/2015/07/01/how-to-use-mocks-in-injected-objects-with-guiceplayscala/

但我正在使用带有 OneAppPerSuite 的 scala 测试使用 FakeApplication 的特征。以下是文档:
https://www.playframework.com/documentation/2.4.x/ScalaFunctionalTestingWithScalaTest

问题是我找不到拦截 GuiceApplicationBuilder 的方法并用模拟实现覆盖一些绑定(bind)。

这里是 FakeApplication来自 play.api.test 的实现:

case class FakeApplication(
  override val path: java.io.File = new java.io.File("."),
  override val classloader: ClassLoader = classOf[FakeApplication].getClassLoader,
  additionalPlugins: Seq[String] = Nil,
  withoutPlugins: Seq[String] = Nil,
  additionalConfiguration: Map[String, _ <: Any] = Map.empty,
  withGlobal: Option[play.api.GlobalSettings] = None,
  withRoutes: PartialFunction[(String, String), Handler] = PartialFunction.empty) extends Application {

private val app: Application = new GuiceApplicationBuilder()
  .in(Environment(path, classloader, Mode.Test))
  .global(withGlobal.orNull)
  .configure(additionalConfiguration)
  .bindings(
    bind[FakePluginsConfig] to FakePluginsConfig(additionalPlugins, withoutPlugins),
    bind[FakeRouterConfig] to FakeRouterConfig(withRoutes))
  .overrides(
    bind[Plugins].toProvider[FakePluginsProvider],
    bind[Router].toProvider[FakeRouterProvider])
  .build

所以我没有办法拦截到GuiceApplicationBuilder并覆盖绑定(bind)。

我是 playframework 的新手,如果问题看起来有点傻,我很抱歉。
谢谢!

最佳答案

您可能使用的是旧版本的 ScalaTestPlus,它不支持使用 Application 覆盖 FakeApplication。在 Play docs ( Play 2.4)库版本是“1.4.0-M3”,但应该是“1.4.0”。

关于scala - 如何使用 ScalaTest 在 Playframework 单元测试中覆盖 guice 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32363644/

相关文章:

scala - 如何让 SBT key 查看当前配置的设置?

scala - 无法执行用户定义的函数($anonfun$9 : (string) => double) on using String Indexer for multiple columns

java - SBT scala 猴子补丁库

java - 使用手动依赖注入(inject)构建多级对象树

unit-testing - 测试重定向 CakePHP 2.0

scala - 有没有一种很好的 Play2 方法可以用 Guice 在 Play 插件中注入(inject)实例

scala - 解决大型 Chisel 文件所触发的 JVM 代码大小限制的任何方法

java - Android PointF 构造函数在 JUnit 测试中不起作用

scala - 如何让 gradle/intellij/play 框架协同工作?

scala - 将 Scala 文件放在 Play Framework 2.0 中的什么位置,以便将其编译为默认包的一部分?