6

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

biesior
  • 55,576
  • 10
  • 125
  • 182
maloku
  • 153
  • 1
  • 7
  • 1
    Maybe this is related: https://github.com/playframework/playframework/issues/4857 – Chris W. Nov 10 '15 at 16:20
  • Indeed, it seems like I am dealing with the same issue. I will try the suggested workaround pointed at your link, and see whether it works. I will update then my question, if I get time to work on it again. Thanks. – maloku Nov 23 '15 at 14:25

1 Answers1

0

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.

  1. https://twitter.github.io/scala_school/specs.html
  2. http://www.scalatest.org/user_guide/using_assertions (for ScalaTest)
  3. http://www.scalatest.org/getting_started_with_fun_suite

Hope this helps!

Arpit Suthar
  • 754
  • 1
  • 5
  • 19