I am trying to test an action on a controller.
It\'s a rather simple action, it takes JSON and returns JSON:
def createGroup = Action(parse.json) {
I had the same problem. Fixed it like this:
"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)
}
Maybe something like:
"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
}
}
}
Note: The val result
line might now be correct since I took it from a test that uses an Async controller.
I am using Play 2.1. @EtienneK method is not working for me. This is how I use:
"update profile with new desc" in {
running(FakeApplication()) {
var member1 = new MemberInfo("testapi2@test.com")
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()
}
}