为 Play websockets 编写单元测试

2024-04-21

我正在使用 websockets 开发 Scala + Play 应用程序。我有一个简单的网络套接字定义如下:

def indexWS =  WebSocket.using[String] { request =>

val out = Enumerator("Hello!")
val in = Iteratee.foreach[String](println).map { _ =>
  println("Disconnected")
}


(in,out)
}

我已经使用 Chrome 的控制台验证了这一点。我遇到的问题是尝试为此编写单元测试。目前我有这个:

"send awk for websocket connection" in {
  running(FakeApplication()){
    val js = route(FakeRequest(GET,"/WS")).get

    status(js) must equalTo (OK)
    contentType(js) must beSome.which(_ == "text/javascript")
  }
}

但是,当在 play 控制台中运行测试时,我收到此错误,其中第 35 行对应于此行 'val js = route(FakeRequest(GET,"/WS")).get':

NoSuchElementException: None.get (ApplicationSpec.scala:35)

我无法找到单元测试 scala/play websockets 的好例子,并且对如何正确编写此测试感到困惑。


受到布鲁斯·洛的回答的启发,这里是另一个例子Hookup http://backchatio.github.io/hookup/:

import java.net.URI
import io.backchat.hookup._
import org.specs2.mutable._
import play.api.test._
import scala.collection.mutable.ListBuffer

class ApplicationSpec extends Specification {

  "Application" should {

    "Test websocket" in new WithServer(port = 9000) {
      val hookupClient = new DefaultHookupClient(HookupClientConfig(URI.create("ws://localhost:9000/ws"))) {
        val messages = ListBuffer[String]()

        def receive = {
          case Connected =>
            println("Connected")

          case Disconnected(_) =>
            println("Disconnected")

          case JsonMessage(json) =>
            println("Json message = " + json)

          case TextMessage(text) =>
            messages += text
            println("Text message = " + text)
        }

        connect() onSuccess {
          case Success => send("Hello Server")
        }
      }

      hookupClient.messages.contains("Hello Client") must beTrue.eventually
    }

  }

}

该示例假设 websocket actor 将回复"Hello Client" text.

要包含该库,请将此行添加到libraryDependencies in build.sbt:

"io.backchat.hookup" %% "hookup" % "0.4.2"

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为 Play websockets 编写单元测试 的相关文章

随机推荐