如何在控制器中进行单元测试?

时间:2015-12-29 10:12:51

标签: scala specs2 playframework-2.4

假设我有以下控制器:

class JenisKejahatanControl @Inject()(service: JenisKejahatanService, val messagesApi: MessagesApi) extends Controller with I18nSupport {

  def add = Action.async { implicit request =>
    lazy val incoming = JenisKejahatan.formJenisK.bindFromRequest()

    incoming.fold( error => {
      lazy val response = ErrorResponse(BAD_REQUEST, messagesApi("request.error"))
      Future.successful(BadRequest(Json.toJson(response)))
    }, { newJenisK =>
      lazy val future = service.addJenisK(newJenisK)
      future.flatMap {
        case Some(jenis) => Future.successful(Created(Json.toJson(SuccessResponse(jenis))))
        case None => Future.successful(BadRequest(Json.toJson(ErrorResponse(NOT_FOUND, messagesApi("add.jenis.kejahatan.fail")))))
      }
    })
  }
}

我想用specs2测试我的def添加,该怎么做?

1 个答案:

答案 0 :(得分:2)

由于您的控制器已经注入了组件,我认为您缺少的一个位是如何在您的规范中获取其实例,并满足各种依赖关系。为此,您可以使用GuiceApplicationBuilder获取Play应用程序实例,然后使用其injector获取控制器实例,而无需手动构建它(更多依赖注入文档here特别是关于使用Guice here进行测试。)

如果你可以手动构建你的控制器,就像在例子中那样,这很好并且使事情更简单,但是控制器往往具有非平凡的依赖关系,你最有可能想要使用overrides方法进行模拟。 GuiceApplicationBuilder

在构建控制器的实例后,将“模拟(假)”请求“应用”到您的操作方法并确定它们给出您期望的状态和正文非常简单。这是一个例子:

import controllers.{SuccessResponse, JenisKejahatanControl}
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.inject.bind
import play.api.mvc.Result
import play.api.test.{FakeRequest, PlaySpecification}

import scala.concurrent.Future

class JenisKejahatanControlSpec extends PlaySpecification {

  "JenisKejahatanControl#add" should {
    "be valid" in {

      // Build an instance of a Play application using the
      // default environment and configuration, and use it
      // to obtain an instance of your controller with the
      // various components injected.
      val jenisController = new GuiceApplicationBuilder()
        .overrides(  // Mock the data service
          bind[JenisKejahatanService]
           .toInstance(new MockJenisKejahatanService))
        .build()
        .injector
        .instanceOf[JenisKejahatanControl]

      // Create a "fake" request instance with the appropriate body data
      val request = FakeRequest().withFormUrlEncodedBody("name" -> "test")

      // Apply the request to your action to obtain a response
      val eventualResult: Future[Result] = jenisController.add.apply(request)

      // Check the status of the response
      status(eventualResult) must_== CREATED

      // Ensure the content of the response is as-expected
      contentAsJson(eventualResult).validate[SuccessResponse].asOpt must beSome.which { r =>
        r.jenis.name must_== "test"
      }
    }
  }
}