【问题标题】:How to test a Play application using Guice and mocking custom ControllerComponents如何使用 Guice 测试 Play 应用程序并模拟自定义 ControllerComponents
【发布时间】:2019-06-12 11:20:59
【问题描述】:

我已经开始构建一个新的 Scala Play!应用程序,我想知道如何测试定义如下的控制器:

class CustomController @Inject()(
    cc: SecuredControllerComponents,
    clientResourceHandler: CustomResourceHandler
)(implicit ec: ExecutionContext)
    extends SecuredController(cc)

我需要模拟 Guice 自动注入的SecuredControllerComponents

case class SecuredControllerComponents @Inject()(
    adminActionBuilder: AdminActionBuilder,
    authenticatedActionBuilder: AuthenticatedActionBuilder,
    actionBuilder: DefaultActionBuilder,
    parsers: PlayBodyParsers,
    messagesApi: MessagesApi,
    langs: Langs,
    fileMimeTypes: FileMimeTypes,
    executionContext: scala.concurrent.ExecutionContext
) extends ControllerComponents

class SecuredController @Inject()(scc: SecuredControllerComponents)
    extends AbstractController(scc) {
  def AdminAction: AdminActionBuilder                       = scc.adminActionBuilder
  def AuthenticatedAction: AuthenticatedActionBuilder       = scc.authenticatedActionBuilder
}

Play 官方文档建议使用Helpers.stubControllerComponents() 将组件传递给必须测试的控制器。

编辑 - 我要执行的测试

    "return a list of Custom Objects as a JSON array" in {
      val controller =
        new CustomController(Helpers.stubControllerComponents(), resourceHandler)
      val result: Future[Result] = controller.index().apply(FakeRequest())
      .....
      val bodyText: String       = contentAsString(result)
      bodyText mustBe "ok"

我已经通过this guide 了解如何使用 Google Guice 进行测试,但我不知道如何处理我的自定义 SecuredComponentsCustomResourceHandler

能否请您指出正确的方向?有什么好的例子可供参考吗?

我目前的配置

  • Scala v2.12.8
  • 播放 2.7.2
  • Scala Guice 4.2.1
  • scalatestplus-play 4.0.2

【问题讨论】:

  • 有几种方法可以测试控制器,您尝试的是哪一种?如果您是直接测试方法或通过调用路由来测试控制器,则发布您的失败测试会对您有所帮助。
  • @AlexITC 我添加了一个我想执行的测试示例。我需要将scc: SecuredControllerComponents 传递给CustomController。你知道一个可能的解决方法吗?我要疯了,虽然它应该是最简单的部分......
  • 正如@AlexITC 在 Gitter 上指出的那样,这个解决方案可以完全解决问题:github.com/X9Developers/block-explorer/blob/develop/server/test/…

标签: scala playframework guice


【解决方案1】:

我认为您现在需要做的就是模拟您的课程,例如使用 Mockito

  new CustomController(mySecuredControllerComponentsMock, myCustomResourceHandlerMock)


 ...

 lazy val mySecuredControllerComponentsMock = {
  mock(SecuredControllerComponents.class)
  ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-13
    • 2018-01-30
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 2020-10-05
    • 2016-03-03
    相关资源
    最近更新 更多