Websocket单元测试:来自ScalaTestRouteTest的WS不会执行websocket请求

问题描述 投票:2回答:1

我正在尝试为websocket进行单元测试。从doc,我应该能够使用WS

见下文sscce

package com.streamingout

import akka.http.scaladsl.model.ws.TextMessage
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.PathMatchers.Rest
import akka.http.scaladsl.testkit.{ScalatestRouteTest, WSProbe}
import akka.stream.scaladsl.{Flow, Sink, Source}
import org.scalatest.{FlatSpec, Matchers}


class Test extends FlatSpec with Matchers with ScalatestRouteTest{


  //--------------- Flow ---------------
  def flow = {
    import scala.concurrent.duration._
    val source =  Source.tick(initialDelay = 0 second, interval = 1 second, tick = TextMessage("tick"))

    Flow.fromSinkAndSource(Sink.ignore, source)
  }


  //-------------- Routing ------------
  def route = {
    path("/wskt") {
      println("websocket ws")
      handleWebSocketMessages(flow)
    } ~
      path(Rest) { pathRest =>
        println("path Rest")
        getFromFile(s"webapp/$pathRest")
      }
  }


  // create a testing probe representing the client-side
  val wsClient = WSProbe()

  // WS creates a WebSocket request for testing
  WS("/wskt", wsClient.flow) ~> route ~> check {
    // check response for WS Upgrade headers
    isWebSocketUpgrade shouldEqual true

  }
}

当我运行测试时,我可以在我的控制台中看到path Rest消息,这意味着WS不会升级到Websocket。

谁知道我的代码有什么问题?

我正在使用akka 2.4.7

谢谢

akka-stream akka-http
1个回答
1
投票

为了使上面的代码工作,在route中,路径/wkst应该没有任何前导斜杠

def route = {
    path("wskt") {
      println("websocket ws")
      handleWebSocketMessages(flow)
    } ~
      path(Rest) { pathRest =>
        println("path Rest")
        getFromFile(s"webapp/$pathRest")
      }
  }
© www.soinside.com 2019 - 2024. All rights reserved.