在单元测试时在播放控制器中注入模拟服务对象的依赖

Inject dependency of mock service object in play controller while unit testing it

我有一个看起来像

的控制器
class MyController @Inject()(service: MyService,
                                 cc: MessagesControllerComponents
                     )(implicit ec: ExecutionContext)
  extends MessagesAbstractController(cc) {

def getAll ....// all methods of controller

现在,我正在尝试使用 Mockito 和 Scalatest 对控制器进行单元测试,我试图在单元测试中注入 MyService 的模拟对象。我的单元测试如下

class MyControllerTest extends PlaySpec with GuiceOneAppPerSuite {

  "MyController" should {

    def fakeApplication(): Application = new GuiceApplicationBuilder().build()

    "not return 404" when {
      "we try to hit the route /ads" in {
        val fakeRequest = FakeRequest(GET, "/ads")
        val futureResult: Future[Result] = route(fakeApplication, fakeRequest).get
        val resultJson: JsValue = contentAsJson(futureResult)(Timeout(2, TimeUnit.SECONDS))
        resultJson.toString mustBe """{"status":"success"}"""
      }
    }
  }
}

现在要对控制器进行单元测试,我需要在通过 guice 构建控制器时传入控制器中的服务模拟。我尝试了以下方法在控制器中注入模拟依赖项,

val application = new GuiceApplicationBuilder()
  .overrides(bind[MyService])
  .build

但是,它未能注入模拟服务对象。任何关于我哪里出错的指示都将受到高度赞赏。提前致谢。

你必须做类似

的事情
val application = new GuiceApplicationBuilder()
  .overrides(bind[MyService].toInstance(yourMock))
  .build