Cristian Boariu
Cristian Boariu

Reputation: 9621

Why test method fails?

I have a create method to create entities trough POST:

  def create = Action(parse.json) { request =>
    val address = Json.fromJson[Address](request.body)
    Ok(address.toString())
  }

I want to test it like:

 "A POST request on addresses create method" should "return OK " in {
    val node = Json.toJson(Address(None, "street 2", "33", "343333", "Arad", "Romania", None))(controllers.AddressBean.addressWrites);
    val result = AddressBean.create(FakeRequest().withJsonBody(node, Helpers.POST))

    status(result) should equal(OK)
    contentType(result) should be(Some("application/json"))
  }

but seems strange to me this warning about status(result):

type mismatch; found : play.api.libs.iteratee.Iteratee[Array[Byte],play.api.mvc.Result] required: play.api.mvc.Result

Does anyone knows why this type mismatch happens?

Upvotes: 2

Views: 364

Answers (1)

Cristian Boariu
Cristian Boariu

Reputation: 9621

I'm posting here the solution I received from James, on google groups, maybe will be useful to others:

Unfortunately this confusion comes from there being two apply methods on Action, one that accepts RequestHeader, and one that accepts Request[A], where A must be the type of the body that the action accepts. Hence, if you pass a request with the wrong body type, it will use the RequestHeader apply method, which is what returns the iteratee.

So, your problem is that your passing the wrong body type. withJsonBody passes a content type of AnyContent, which is what gets used when you don't explicitly specify a parser in your action. But you're using parse.json, which means the body is a JsonNode. So, try something like this:

new FakeRequest(Helpers.POST, "/", FakeHeaders(), node)

so in the end my POST test method (using scalatest) looks like:

    "A POST request on addresses create method" should "return OK " in {
    val node = Json.toJson(Address(Some(12), "street 2", "33", "343333", "Arad", "Romania", None))(controllers.AddressBean.addressWrites);
    val result = AddressBean.create(new FakeRequest(Helpers.POST, "/", FakeHeaders(), node))

    status(result) should equal(OK)
    contentType(result) should be(Some("application/json"))
  }

Upvotes: 3

Related Questions