我有以下动作
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"))
}
我想测试一下
Web 服务可以正常使用 curl,如下所示:
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)
任何的想法?