2015-07-16 12 views
6

Ho implementato il mio HttpErrorHander in Play Framework 2.4.2 e funziona molto bene, ma ora voglio essere in grado di testare "Azioni false" che lanciano intenzionalmente eccezioni. Ho provato in scalatest e specs2Test HttpErrorHandler con scale/specs2 in Play Framework 2.4.2

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

ho provato finora le seguenti prove. Provo a eseguire il debug del codice, ma non inserisco mai i miei metodi. I metodi di play.api.http.DefaultHttpErrorHandler non vengono eseguiti.

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

L'azione-metodo TestController.exceptionAction osserva:

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

Il secondo tentativo:

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

    } 
} 

E il percorso per /exception

GET  /exception    controllers.TestController.exceptionAction 

Ho anche aggiunto in 012.play.http.errorHandler. Ma come ho detto, funziona, ma non sono in grado di testarlo. Il test fallisce sempre con l'eccezione data in exceptionAction.

Grazie in anticipo

+1

Forse questo è relativo: https://github.com/playframework/playframework/issues/4857 – longliveenduro

+0

In effetti, sembra che mi sto occupando dello stesso problema. Proverò la soluzione suggerita puntata sul tuo link e vedrò se funziona. Aggiornerò quindi la mia domanda, se avrò tempo per lavorarci di nuovo. Grazie. – maloku

risposta