在Play Framework 2.4.2中使用scalates / specs2测试HttpErrorHandler

时间:2015-07-16 22:52:03

标签: scala playframework scalatest specs2 playframework-2.4

我在Play Framework 2.4.2中实现了自己的HttpErrorHander,它运行得很好,但现在我希望能够使用故意抛出异常的“Fake Actions”进行测试。我试过scalatestspecs2

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)
    )
  }
}

我到目前为止尝试了以下测试。我尝试调试代码,但我从不输入我的方法。 play.api.http.DefaultHttpErrorHandler的方法既未执行。

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:"
    }
  }
}

TestController.exceptionAction中的操作方法看起来:

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

第二次尝试:

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)
   }

  }
}

/exception

的路线
GET        /exception               controllers.TestController.exceptionAction

我还添加了application.conf play.http.errorHandler。但正如我所说,这是有效的,但我无法测试它。测试总是因exceptionAction中给出的异常而失败。

提前谢谢

1 个答案:

答案 0 :(得分:0)

如果您使用的是Specs2,请尝试使用

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

请参阅这些链接。

  1. https://twitter.github.io/scala_school/specs.html
  2. http://www.scalatest.org/user_guide/using_assertions(适用于ScalaTest)
  3. http://www.scalatest.org/getting_started_with_fun_suite
  4. 希望这有帮助!