Akka-http: Unable to test a NotFound status coming from rejectEmptyResponse directive

Created on 11 Jan 2017  路  2Comments  路  Source: akka/akka-http

I have a route returning a Future[Option[Resource]]. I have wrapped the complete call with the rejectEmptyResponse directive.

My rejectionHandler is something like this

 implicit def rejectionHandler = RejectionHandler.newBuilder()
    .handleNotFound {
      val errorResponse = JsObject("message" -> JsString("The requested resource could not be found.")).toString()
      complete(HttpResponse(NotFound, entity = HttpEntity(ContentTypes.`application/json`, errorResponse)))
    }
    .handle { case ValidationRejection(msg, _) => complete((BadRequest, JsObject("message" -> JsString(msg)))) }
    .result()

When I run my service, the route works as expected: when the return is a Future[None] a 404 response is returned.

I would like to add a unit test like this:

"resources" should {
    "return a 404 response when not found" in {
      Get("/resources/0") ~> routes ~> check {
        status.intValue() should be(404)
      }
    }
  }

The test fails though because the Request was rejected

Request was rejected
ScalaTestFailureLocation: akka.http.scaladsl.testkit.RouteTestResultComponent$RouteTestResult at (RouteTestResultComponent.scala:51)
org.scalatest.exceptions.TestFailedException: Request was rejected
    at akka.http.scaladsl.testkit.TestFrameworkInterface$Scalatest.failTest(TestFrameworkInterface.scala:24)
    at akka.http.scaladsl.testkit.TestFrameworkInterface$Scalatest.failTest$(TestFrameworkInterface.scala:24)

Most helpful comment

This works as intended.
The RoutingSpec emits the rejection NOT the "final HttpResponse". This is a feature - you can test if the right rejection was emitted, not the actual response.

If you want to see the actual response: ~> Route.seal(routes) ~>

Read up about sealing and rejections in the docs. If the docs are lacking a PR adding an explanation like this would be cool, thanks in advance!

All 2 comments

This works as intended.
The RoutingSpec emits the rejection NOT the "final HttpResponse". This is a feature - you can test if the right rejection was emitted, not the actual response.

If you want to see the actual response: ~> Route.seal(routes) ~>

Read up about sealing and rejections in the docs. If the docs are lacking a PR adding an explanation like this would be cool, thanks in advance!

You can test rejections like this: rejection should equal (...) inside the check block.

Was this page helpful?
0 / 5 - 0 ratings