我试图在控制器上测试一个动作.
这是一个相当简单的操作,需要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))
))
}
Run Code Online (Sandbox Code Playgroud)
我想验证返回的JSON确实是正确的.
我如何使用FakeRequest来做到这一点?
Jam*_*ard 20
也许是这样的:
"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
}
}
}
Run Code Online (Sandbox Code Playgroud)
注意:val result由于我从使用Async控制器的测试中获取了该行,因此该行现在可能是正确的.
我正在使用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()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14325 次 |
| 最近记录: |