HttpErrorHandler test with / specs 2 scaling in Play Framework 2.4.2

I implemented my own HttpErrorHander on the Play Framework 2.4.2, and it works very well, but now I want to be able to check with the "Fake Actions" that deliberately throw Exceptions. I tried in scalatest and specs2

 import play.api.http.HttpErrorHandler import play.api.mvc._ import play.api.mvc.Results._ import scala.concurrent._ class MyErrorHandler extends HttpErrorHandler { def onClientError(request: RequestHeader, statusCode: Int, message: String) = { Future.successful( Status(statusCode)("A client error occurred: " + message) ) } def onServerError(request: RequestHeader, exception: Throwable) = { Future.successful( InternalServerError("A server error occurred: " + exception.getMessage) ) } } 

I have tried so far the following tests. I am trying to debug the code, but I never go into my methods. The play.api.http.DefaultHttpErrorHandler methods play.api.http.DefaultHttpErrorHandler not execute.

 object ThrowableControllerSpec extends PlaySpecification with Results { "Example Page" should { "throwErrorAction should be valid" in { val controller = new TestController() val result: Future[Result] = controller.exceptionAction().apply(FakeRequest()) //val bodyText: String = contentAsString(result) status(result) mustEqual INTERNAL_SERVER_ERROR //bodyText must be startingWith "A server error occurred:" } } } 

The action method in TestController.exceptionAction looks like this:

 def exceptionAction() = Action { if (true) throw new Exception("error") else Ok("") } 

Second attempt:

 class ApplicationSpec extends Specification { "Application" should { "sent 500 on server error" in new WithApplication { route(FakeRequest(GET, "/exception")) must beSome.which(status(_) == INTERNAL_SERVER_ERROR) } } } 

And the route for /exception

 GET /exception controllers.TestController.exceptionAction 

I also added play.http.errorHandler to application.conf . But, as I said, it works, but I can’t verify it. The test always fails with the Exception specified in exceptionAction .

Thank you in advance

+6
source share
1 answer

If you are using Specs2, try this

 await(controller.exceptionAction()(FakeRequest())) must throwA[Throwable] // or any error you want to test against 

See these links.

Hope this helps!

0
source

All Articles