I have implemented my own HttpErrorHander in Play Framework 2.4.2 and it functions very well, but now I want to be able to test with "Fake Actions" that intentionally throw Exceptions. I have 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 tried so far the following tests. I try to debug the code, but I am never entering my methods. The methods of play.api.http.DefaultHttpErrorHandler
are neither executed.
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:
def exceptionAction() = Action {
if (true)
throw new Exception("error")
else
Ok("")
}
The second try:
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 in application.conf
play.http.errorHandler
. But as I said, this is working, but I am not able to test it. The test always fails with the Exception given in exceptionAction
.
Thank you in advance