How test the websocket?

Hi all

I’ve created a websocket as the following:


import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.ws.{BinaryMessage, Message, TextMessage}
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer
import akka.stream.scaladsl.{Flow, Sink, Source}

import scala.io.StdIn

object WebServer {

  def messenger(implicit materializer: ActorMaterializer): Flow[Message, Message, Any] =
    Flow[Message].mapConcat {
      case tm: TextMessage =>
        TextMessage(tm.textStream) :: Nil
      case bm: BinaryMessage =>
        // ignore binary messages but drain content to avoid the stream being clogged
        bm.dataStream.runWith(Sink.ignore)
        Nil
    }


  def main(args: Array[String]) {

    implicit val system = ActorSystem("sapbroker")
    implicit val materializer = ActorMaterializer()
    // needed for the future flatMap/onComplete in the end
    implicit val executionContext = system.dispatcher

    val route =
      pathSingleSlash {
        get {
          complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, "<h1>Welcome to SAP broker.</h1>"))
        }
      } ~ path("sap") {
        handleWebSocketMessages(messenger)
      }

    val bindingFuture = Http().bindAndHandle(route, "localhost", 8080)

    println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
    StdIn.readLine() // let it run until user presses return
    bindingFuture
      .flatMap(_.unbind()) // trigger unbinding from the port
      .onComplete(_ => system.terminate()) // and shutdown when done
  }
}

How to write the test for the websocket?

Thanks

See the snippet in this paragraph of the documentation which contains code for testing WS services.

1 Like

Hi!
Looks like that code assumes something that is not mentioned in the documentation.
It requires to import akka.http.scaladsl.server.RoutingSpec
but

not found: type RoutingSpec
[error] class ServerTest extends RoutingSpec  {
[error]                          ^

Thanks!

Working imports are:

import akka.http.scaladsl.testkit.{ ScalatestRouteTest, WSProbe }
import org.scalatest.{ Matchers, WordSpec }

import scala.concurrent.duration._

class WebServerTest extends WordSpec with Matchers with ScalatestRouteTest {
1 Like