Question

I want to unit test a controller method that returns an EssentialAction. I pass a FakeRequest to it, and get back a Iteratee[Array[Byte], Result].

It looks like the test helpers contentAsString, contentType and status do not accept this result type.

Is there an implicit conversion I am missing? Is there an example somewhere of controllers being unit tested without bringing up an entire FakeApplication?

Was it helpful?

Solution

An essential action is a RequestHeader => Iteratee[Indata, Result], you can apply it to FakeRequest since it implements RequestHeader. To actually execute the iteratee you either stuff it with data or just tell it right away that there is no more indata. For both those cases you get a Future[Result] back which you need to wait for in the tests.

So, for a simple GET with no request body (using the play test helper await method) you could do it like this:

val iteratee = controllers.SomeController.action()(FakeRequest())
val result: Result = await(iteratee.run)

If you want to do requests with request bodies you will have to do some more stuff to be able to feed the request body to the iteratee and also take care of encoding data your indata correctly.

OTHER TIPS

In Play 2.3, PlaySpecification includes a couple of helper methods. In order to handle EssentialActions, you'd use call. The resulting future is handled by other more specific helpers.

class MySpec extends PlaySpecification {
  ...
  val result1: Result = call(controllers.SomeController.action(), FakeRequest(...))
  status(of = result1) must equalTo (OK)
  ...
  val result2 = call(controllers.SomeController.action(), RequestHeader(...), "Body")
  status(of = result2) must equalTo (BAD_REQUEST)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top