Question

I'm working on getting a test case working with Play 2.1.1 and Specs2 and am running into an interesting problem. I create a FakeRequest to send to a Controller, but the function in the controller never gets called.

Here's the test code (slightly simplified, but with all the moving parts):

"controller" should {
"do something" in new WithApplication {
    val controller = new MyController()
    controller.main() { 
        new FakeRequest(
            PUT,
            routes.MyController.main().toString,
            new FakeHeaders(Seq("Content-Type" -> Seq("text/xml"))),
            AnyContentAsXml(<xml>xml</xml>)
        )
    }       
}

And here's the main function in the controller (well, at least just the start of it):

def main() = Action(BodyParsers.parse.xml) { request =>
    println("main")
}

This code never hits main. Strangely enough, though, if I make the FakeHeader with no parameters, and remove AnyContentAsXml, just sending the Xml Element to the controller, then it works:

new FakeRequest(
    PUT,
    routes.MyController.main().toString,
    new FakeHeaders,
    <xml>xml</xml>
)

Does anyone have any idea why this would happen?

Was it helpful?

Solution

Here is your test little modified showing two ways testing the controller. The reason AnyContentAsXml is not working for you because your testing is mixing two approaches together.

"one way" in new WithApplication {
    val action = controllers.Application.main
    val req: FakeRequest[scala.xml.NodeSeq] = new FakeRequest(
            PUT,
            "some url",
            new FakeHeaders(Seq("Content-Type" -> Seq("text/xml"))),
            <xml>xml</xml>
        )
    val x = action(req)
    status(x) should beEqualTo(200)
}

"2nd way" in new WithApplication {
  val Some(result) = route(new FakeRequest("PUT", 
      "/", 
      new FakeHeaders(Seq("Content-Type" -> Seq("text/xml"))),
      AnyContentAsXml(<xml>xml</xml>)))
  status(result) should beEqualTo(200)
}

}

In the second approach Play is take care of unpacking the xml for the BodyParser to use. And here is the controller:

def main = Action(BodyParsers.parse.xml) { request =>
   println(">>>>>>>>>>>>>>>>>>> main")
  Ok("")
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top