即使结果不匹配,PlaySpec测试也会通过

时间:2018-06-09 10:22:29

标签: asynchronous scalatest playframework-2.6

我写了以下规范。令人惊讶的是,即使结果不匹配也会通过

代码段

  val controller = new UserController(mockUserRepository,mockControllerComponents,mockSilhouette)
  //val request = FakeRequest[AnyContentAsJson]("POST", "/ws/users/signup").withJsonBody(Json.parse("""{"bad": "field"}"""))//FakeRequest(POST,"/ws/users/signup").withJsonBody(Json.parse("""{"bad":"field"}"""));
  val request = FakeRequest("POST","ws/users/signup")
  println("sending request",request)
  //val result = controller.someMethod()
  val result = controller.signupUser(request)

  Await.result(result,Duration("10 secs"))
  result.map(response => {
    println("response from controller:"+response)
    response mustBe play.api.mvc.Results.BadRequest
  })

控制台打印 (sending request,POST ws/users/signup)

在控制器中打印。 (received request,POST ws/users/signup)

Controller返回200OK,但我将其与BadRequest匹配。测试仍然通过! response from controller:Result(200, Map())

我怀疑我没有正确匹配结果。我在做response mustBe play.api.mvc.Results.BadRequest。我知道responseResultsBadRequestStatus。但我不知道如何匹配,以及为什么测试不会失败。我也试过跟随,可以看到值不同,但即使这样,测试也通过了。

  println("response from controller:"+response.header.status+" compared with "+play.api.mvc.Results.BadRequest.header.status)
        response.header.status mustBe play.api.mvc.Results.BadRequest.header.status

控制台打印 - response from controller:200 compared with 400

1 个答案:

答案 0 :(得分:0)

导入Helpers对象的成员,如此

import play.api.test.Helpers._

可以在测试中访问来自Future[Result]的{​​{3}}结果的各种实用程序方法。例如,Helpers.status可用于提取状态代码,如下所示:

val result: Future[Result] = controller.signupUser(request)
status(result) mustBe BAD_REQUEST

另一种选择是使用extract中的whenReady

val result: Future[Result] = controller.signupUser(request)
whenReady(result) { _.header.status mustBe BAD_REQUEST }

另一种选择是扩展ScalaFutures,然后您可以映射Future,如下所示:

val result: Future[Result] = controller.signupUser(request)
result.map(_.header.status mustBe BAD_REQUEST)