播放框架2:使用json字符串作为正文测试请求

时间:2012-10-29 06:01:42

标签: scala testing playframework-2.0 specs2

我有以下行动

def save() = Action(parse.json) { implicit request =>
  request.body.asOpt[IdeaType].map { ideatype =>
    ideatype.save.fold(
      errors => JsonBadRequest(errors),
      ideatype => Ok(toJson(ideatype))
    )
  }.getOrElse     (JsonBadRequest("Invalid type of idea entity"))
}

我想测试一下

网络服务正常运行,如下所示:

curl -X post "http://localhost:9000/api/types" 
--data "{\"name\": \"new name\", \"description\": \"new description\"}" 
--header "Content-type: application/json"

正确返回新资源

{"url":"/api/types/9","id":9,"name":"new name","description":"new description"}

我正试图用

测试它
"add a new ideaType, using route POST /api/types" in {
  running(FakeApplication(additionalConfiguration = inMemoryDatabase())) {

    val json = """{"name": "new name", "description": "new description"}"""

    val Some(result) = routeAndCall(
      FakeRequest(
        POST, 
        "/api/types",
        FakeHeaders(Map("Content-Type" -> Seq("application/json"))), 
        json
      )
    )

    status(result) must equalTo(OK)
    contentType(result) must beSome("application/json")
    val Some(ideaType) = parse(contentAsString(result)).asOpt[IdeaType]

    ideaType.name mustEqual "new name"

  }
}

但我收到以下错误:

[error] ! add a new ideaType, using route POST /api/types
[error]     ClassCastException: java.lang.String cannot be cast to play.api.libs.json.JsValue (IdeaTypes.bak.scala:35)
[error] controllers.IdeaTypes$$anonfun$save$1.apply(IdeaTypes.bak.scala:36)
[error] controllers.IdeaTypes$$anonfun$save$1.apply(IdeaTypes.bak.scala:35)
[error] play.api.mvc.Action$$anon$1.apply(Action.scala:170)

我遵循了这个问题的建议:Play 2 - Scala FakeRequest withJsonBody

我错过了什么吗?

-

Kim Stebel解决方案运行良好,但后来我尝试使用withJsonBody,就像这样:

    val jsonString = """{"name": "new name", "description": "new description"}"""
    val json: JsValue = parse(jsonString)

    val Some(result) = routeAndCall(
      FakeRequest(POST, "/api/types").
      withJsonBody(json)
    )

我收到以下错误:

[error] ! add a new ideaType, using route POST /api/types
[error]     ClassCastException: play.api.mvc.AnyContentAsJson cannot be cast to play.api.libs.json.JsValue (IdeaTypes.bak.scala:35)
[error] controllers.IdeaTypes$$anonfun$save$1.apply(IdeaTypes.bak.scala:36)
[error] controllers.IdeaTypes$$anonfun$save$1.apply(IdeaTypes.bak.scala:35)

任何想法?

1 个答案:

答案 0 :(得分:9)

您可能需要传入JsValue作为请求的正文。改变行

val json = """{"name": "new name", "description": "new description"}"""

val jsonString = """{"name": "new name", "description": "new description"}"""
val json = Json.parse(jsonString)