播放2-使用JsonBody的Scala FakeRequest [英] Play 2 - Scala FakeRequest withJsonBody

查看:45
本文介绍了播放2-使用JsonBody的Scala FakeRequest的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to test an action on a controller.

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

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

我要验证返回的JSON确实正确.

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

我将如何使用FakeRequest做到这一点?

How would I use FakeRequest to do this?

推荐答案

也许是这样的:

"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行现在可能是正确的,因为我是从使用异步控制器的测试中获得的.

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

这篇关于播放2-使用JsonBody的Scala FakeRequest的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆