gpt4 book ai didi

unit-testing - 编写Play网络套接字的单元测试

转载 作者:行者123 更新时间:2023-12-04 03:38:17 25 4
gpt4 key购买 nike

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

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 websocket的例子,并且对如何正确编写此测试感到困惑。

最佳答案

受bruce-lowe的回答启发,这是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参与者将使用 "Hello Client"文本进行回复。

要包含库,请将此行添加到 libraryDependencies中的 build.sbt中:
"io.backchat.hookup" %% "hookup" % "0.4.2"

关于unit-testing - 编写Play网络套接字的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19306787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com