Play framework 2: check request using json string as body

I have the following action

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

And I would like to test it

The web service works fine with curl:

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

which correctly returns a new resource

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

I try to check it with

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

But I get the following error:

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

I followed advice on this issue: Play 2 - Scala FakeRequest withJsonBody

Did I miss something?

-

Kim Stebel's solution worked fine, but then I tried using JsonBody, for example:

  val jsonString = """{"name": "new name", "description": "new description"}""" val json: JsValue = parse(jsonString) val Some(result) = routeAndCall( FakeRequest(POST, "/api/types"). withJsonBody(json) ) 

and I get the following error:

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

any idea?

+6
source share
1 answer

You probably need to pass JsValue as the request body. Change the line

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

to

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

All Articles