我有一个控制器,看起来像
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