我在Play Framework 2.4.2中实现了自己的HttpErrorHander,它运行得很好,但现在我希望能够使用故意抛出异常的“Fake Actions”进行测试。我试过scalatest
和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)
)
}
}
我到目前为止尝试了以下测试。我尝试调试代码,但我从不输入我的方法。 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
中给出的异常而失败。
提前谢谢
答案 0 :(得分:0)
如果您使用的是Specs2,请尝试使用
await(controller.exceptionAction()(FakeRequest())) must throwA[Throwable] // or any error you want to test against
请参阅这些链接。