2012-08-10 10 views
19

Sto provando a testare un'azione su un controller.Play 2 - Scala FakeRequest withJsonBody

Si tratta di un'azione piuttosto semplice, ci vuole JSON e restituisce 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)) 
    )) 
    } 

voglio verificare che il JSON restituito è davvero corretto.

Come utilizzare FakeRequest per eseguire questa operazione?

+0

simile: http://stackoverflow.com/questions/28247112/playframework-fakerequest-reuturns-400-error – ses

risposta

19

Forse qualcosa di simile:

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

Nota: La linea val result potrebbe ora essere corretto in quanto l'ho preso da un test che utilizza un controller asincrono.

+1

ha lavorato per me quando all'interno 'FakeRequest' il' body' è stata impostata essere un JsValue (è stato analizzato) piuttosto che una semplice stringa –

+1

non riesce su ".result.value" per me. evidenzia "result" – ses

+0

'FakeHeaders()' non funziona in 2.6 perché l'intestazione 'host' non è presente causa di dare un avvertimento di sicurezza e rifiutare la richiesta.Inoltre, l'intestazione del tipo di contenuto deve essere impostata su text/json. Quindi quello che ho dovuto fare è: 'val postHeaders = FakeHeaders (List (" HOST ") -> "localhost", "content-type" -> "text/json")), quindi: 'FakeRequest (POST, path, postHeaders, body)' –

4

Ho avuto lo stesso problema. Risolto il problema:

"respond to the register Action" in { 
    val requestNode = Json.toJson(Map("name" -> "Testname")) 
    val request = FakeRequest().copy(body = requestNode) 
     .withHeaders(HeaderNames.CONTENT_TYPE -> "application/json"); 
    val result = controllers.Users.register()(request) 

    status(result) must equalTo(OK) 
    contentType(result) must beSome("application/json") 
    charset(result) must beSome("utf-8") 

    val responseNode = Json.parse(contentAsString(result)) 
    (responseNode \ "success").as[Boolean] must equalTo(true) 
    } 
+0

restituito iteratee invece di 'Si mpleResult' – zinking

8

Sto usando Play 2.1. Il metodo @EtienneK non funziona per me. Questo è il modo che uso:

"update profile with new desc" in { 
      running(FakeApplication()) { 
     var member1 = new MemberInfo("[email protected]") 
     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() 
     } 
    } 
Problemi correlati