我有一个看起来像
的控制器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
但是,它无法注入模拟的服务对象。任何关于我要去哪里的指示都将受到高度赞赏。预先感谢。
答案 0 :(得分:0)
您必须做类似的事情
val application = new GuiceApplicationBuilder()
.overrides(bind[MyService].toInstance(yourMock))
.build