Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stanislav-chetvertkov/4e32a05d37a327a8dda7fa2eff053f49 to your computer and use it in GitHub Desktop.
Save stanislav-chetvertkov/4e32a05d37a327a8dda7fa2eff053f49 to your computer and use it in GitHub Desktop.
Akka Http Mock Server
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{HttpRequest, HttpResponse, Uri}
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Sink, Source}
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
/**
* Mock Akka HTTP Server, will handle requests which is provided with handle request
*/
object MockServer {
def handleRequestWithHandler(requestHandler: HttpRequest => HttpResponse, port: Int = 0)
(implicit system: ActorSystem, mt: ActorMaterializer): Future[Http.ServerBinding] = {
val serverSource: Source[Http.IncomingConnection, Future[Http.ServerBinding]] =
Http().bind(interface = "localhost", port = port)
serverSource.to(Sink.foreach { connection =>
println("Mock Server accepted new connection from " + connection.remoteAddress)
connection handleWithSyncHandler requestHandler
}).run()
}
object withMockServer {
def apply(handler: HttpRequest => HttpResponse, port: Int = 2345)(block: => Unit)
(implicit setupDuration: FiniteDuration, system: ActorSystem): Unit = {
implicit val mt = ActorMaterializer()
val binding = Await.result(MockServer.handleRequestWithHandler(requestHandler = handler, port = port), setupDuration)
block
Await.result(binding.unbind(), setupDuration)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment