Search code examples
jsonplayframeworkspec2

How to unit test controller action with json body?


Lets say I have a case class with json writer provided

val song1 = Song("Song one", "Artist 1", "Song url 1")

I then try to invoke a controller action create with parser Action(parse.json)

adminController.create(FakeRequest().withHeaders(CONTENT_TYPE -> "text/json").withJsonBody(Json.toJson(song1))).run

I got an error

[Invalid Json: No content to map due to end-of-inpu at [Source: [B@1ad542ff; line: 1, column: 1]]

What am I missing?


Solution

  • It seems that the .withJsonBody is meant for internal use. Just use

    val json = /* some JsValue */
    FakeRequest().withBody(json)
    

    and the request will be automatically parsed correctly with the correct headers.