How to test client-side Akka HTTP

前端 未结 3 1560
挽巷
挽巷 2021-02-07 09:55

I\'ve just started testing out the Akka HTTP Request-Level Client-Side API (Future-Based). One thing I\'ve been struggling to figure out is how to write a unit test for this. Is

3条回答
  •  生来不讨喜
    2021-02-07 10:46

    Considering that you indeed want to write a unit test for your HTTP client you should pretend there is no real server and not cross the network boundary, otherwise you will obviously do integration tests. A long known recipe of enforcing a unit-testable separation in such cases as yours is to split interface and implementation. Just define an interface abstracting access to an external HTTP server and its real and fake implementations as in the following sketch

    import akka.actor.Actor
    import akka.pattern.pipe
    import akka.http.scaladsl.HttpExt
    import akka.http.scaladsl.model.{HttpRequest, HttpResponse, StatusCodes}
    import scala.concurrent.Future
    
    trait HTTPServer {
      def sendRequest: Future[HttpResponse]
    }
    
    class FakeServer extends HTTPServer {
      override def sendRequest: Future[HttpResponse] =
        Future.successful(HttpResponse(StatusCodes.OK))
    }
    
    class RealServer extends HTTPServer {
    
      def http: HttpExt = ??? //can be passed as a constructor parameter for example
    
      override def sendRequest: Future[HttpResponse] =
        http.singleRequest(HttpRequest(???))
    }
    
    class HTTPClientActor(httpServer: HTTPServer) extends Actor {
    
      override def preStart(): Unit = {
        import context.dispatcher
        httpServer.sendRequest pipeTo self
      }
    
      override def receive: Receive = ???
    }
    

    and test your HTTPClientActor in conjunction with FakeServer.

提交回复
热议问题