如何测试Scala Play Framework websocket?

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

如果我有像下面这样的websocket:

def websocket: WebSocket = WebSocket.accept[String, String] { _ =>
  ActorFlow.actorRef(out => LightWebSocketActor.props(out))
}

作为参考,这是LightWebSocketActor

class LightWebSocketActor(out: ActorRef) extends Actor {
  val topic: String = service.topic

  override def receive: Receive = {
    case message: String =>
      play.Logger.debug(s"Message: $message")
      PublishService.publish("true")
      out ! message
  }
}

object LightWebSocketActor {
  var list: ListBuffer[ActorRef] = ListBuffer.empty[ActorRef]
  def props(out: ActorRef): Props = {
    list += out
    Props(new LightSocketActor(out))
  }

  def sendMessage(message: String): Unit = {
    list.foreach(_ ! message)
  }
}

这是使用akka websocket方法。

  • 如何创建这种控制器的测试?
  • 我应该如何发送信息以期待回复?
  • 应该在虚假请求中发送什么样的信息?

例如,我对常规的html返回控制器进行了此测试:

"Application" should {
  "render the index page" in new WithApplication {
    val home = route(app, FakeRequest(GET, "/")).get
    status(home) must equalTo(OK)
    contentType(home) must beSome.which(_ == "text/html")
    contentAsString(home) must contain ("shouts out")
  }
}
scala unit-testing playframework specifications playframework-2.5
1个回答
4
投票

玩2.6

我按照这个例子:play-scala-websocket-example

主要步骤:

创建或提供可在您的网站中使用的WebSocketClient 试验。

创建客户端:

val asyncHttpClient: AsyncHttpClient = wsClient.underlying[AsyncHttpClient]
val webSocketClient = new WebSocketClient(asyncHttpClient)

连接到serverURL

val listener = new WebSocketClient.LoggingListener(message => queue.put(message))
val completionStage = webSocketClient.call(serverURL, origin, listener)
val f = FutureConverters.toScala(completionStage)

测试服务器发送的消息:

whenReady(f, timeout = Timeout(1.second)) { webSocket =>
  await().until(() => webSocket.isOpen && queue.peek() != null)

  checkMsg1(queue.take())
  checkMsg2(queue.take())
  assert(queue.isEmpty)
}

例如,像:

  private def checkMsg1(msg: String) {
    val json: JsValue = Json.parse(msg)
    json.validate[AdapterMsg] match {
      case JsSuccess(AdapterNotRunning(None), _) => // ok
      case other => fail(s"Unexpected result: $other")
    }
  }

整个例子可以在这里找到:scala-adapters(JobCockpitControllerSpec)

© www.soinside.com 2019 - 2024. All rights reserved.