玩2 - Scala FakeRequest withJsonBody

时间:2012-08-10 23:15:07

标签: playframework

我正在尝试在控制器上测试操作。

这是一个相当简单的操作,需要JSON并返回JSON:

  def createGroup = Action(parse.json) { request =>
    val name = (request.body \ "name").as[String]
    val collabs = (request.body \ "collabs").as[List[String]]


    Ok(Json.toJson(
      Map("status" -> "OK",
        "message" -> "%s created".format(name))
    ))
  }

我想验证返回的JSON确实是正确的。

我如何使用FakeRequest来执行此操作?

3 个答案:

答案 0 :(得分:19)

可能是这样的:

"POST createGroup with JSON" should {
  "create a group and return a message" in {
    implicit val app = FakeApplication()
    running(app) {
      val fakeRequest = FakeRequest(Helpers.POST, controllers.routes.ApplicationController.createGroup().url, FakeHeaders(), """ {"name": "New Group", "collabs": ["foo", "asdf"]} """)

      val result = controllers.ApplicationController.createGroup()(fakeRequest).result.value.get

      status(result) must equalTo(OK)
      contentType(result) must beSome(AcceptExtractors.Accepts.Json.mimeType)

      val message = Region.parseJson(contentAsString(result))

      // test the message response
    }
  }
}

注意:val result行现在可能是正确的,因为我从使用异步控制器的测试中获取了它。

答案 1 :(得分:8)

我正在使用Play 2.1。 @EtienneK方法对我不起作用。这就是我的用法:

"update profile with new desc" in {
            running(FakeApplication()) {
        var member1 = new MemberInfo("testapi2@test.com")
        member1.save()
        var mId = member1.getMemberIdString()

        val json = Json.obj(
            "description" -> JsString("this is test desc")
                 )
        val req = FakeRequest(
                  method = "POST",
                  uri = routes.ProfileApiV1.update(mId).url,
                  headers = FakeHeaders(
                    Seq("Content-type"->Seq("application/json"))
                  ),
                  body =  json
                )
                val Some(result) = route(req.withCookies(Cookie("myMemberId", mId)))
        status(result) must equalTo(OK)
        contentType(result) must beSome("application/json")
        charset(result) must beSome("utf-8")
        contentAsString(result) must contain("ok")

        member1 = MemberInfo.getMemberInfoByMemberId(mId)
        member1.delete()
        }
    }

答案 2 :(得分:4)

我遇到了同样的问题。修正如下:

"respond to the register Action" in {
    val requestNode = Json.toJson(Map("name" -> "Testname"))
    val request = FakeRequest().copy(body = requestNode)
        .withHeaders(HeaderNames.CONTENT_TYPE -> "application/json");
    val result = controllers.Users.register()(request)

    status(result) must equalTo(OK)
    contentType(result) must beSome("application/json")
    charset(result) must beSome("utf-8")

    val responseNode = Json.parse(contentAsString(result))
    (responseNode \ "success").as[Boolean] must equalTo(true)
  }