玩 2 - Scala FakeRequest withJsonBody [英] Play 2 - Scala FakeRequest withJsonBody
本文介绍了玩 2 - Scala FakeRequest withJsonBody的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在控制器上测试操作.
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 - Scala FakeRequest withJsonBody的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文