Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play 2 - Scala FakeRequest withJsonBody

I am trying to test an action on a controller.

It's a rather simple action, it takes JSON and returns 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))
    ))
  }

I want to verify that the JSON returned is indeed correct.

How would I use FakeRequest to do this?

like image 765
Hakkar Avatar asked Aug 10 '12 23:08

Hakkar


3 Answers

Maybe something like:

"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
    }
  }
}

Note: The val result line might now be correct since I took it from a test that uses an Async controller.

like image 132
James Ward Avatar answered Nov 02 '22 03:11

James Ward


I am using Play 2.1. @EtienneK method is not working for me. This is how I use:

"update profile with new desc" in {
            running(FakeApplication()) {
        var member1 = new MemberInfo("[email protected]")
        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()
        }
    }
like image 8
angelokh Avatar answered Nov 02 '22 03:11

angelokh


I had the same problem. Fixed it like this:

"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)
  }
like image 4
EtienneK Avatar answered Nov 02 '22 03:11

EtienneK