编写Play网络套接字的单元测试 [英] Writing a unit test for Play websockets
问题描述
我正在使用websockets开发Scala + Play应用程序.我有一个简单的Web套接字定义为:
I am working on a Scala + Play application utilizing websockets. I have a simple web socket defined as such:
def indexWS = WebSocket.using[String] { request =>
val out = Enumerator("Hello!")
val in = Iteratee.foreach[String](println).map { _ =>
println("Disconnected")
}
(in,out)
}
我已使用Chrome的控制台验证了此功能.我遇到的问题是试图为此编写单元测试.目前我有这个:
I have verified this works using Chrome's console. The issue I'm having is trying to write a unit test for this. Currently I have this:
"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':
However, when running my tests in play console, I receive this error, where line 35 corresponds to this line 'val js = route(FakeRequest(GET,"/WS")).get':
NoSuchElementException: None.get (ApplicationSpec.scala:35)
我无法找到一个很好的单元测试scala/play websocket的例子,并且对如何正确编写此测试感到困惑.
I have not been able to find a good example of unit testing scala/play websockets and am confused on how to properly write this test.
推荐答案
受bruce-lowe的回答启发,这是联播:
Inspired by answer from bruce-lowe, here is the alternative example with 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"
文本.
The example assumed the websocket actor would reply with "Hello Client"
text.
要包含库,请将此行添加到build.sbt
中的libraryDependencies
:
To include the library, add this line to libraryDependencies
in build.sbt
:
"io.backchat.hookup" %% "hookup" % "0.4.2"
这篇关于编写Play网络套接字的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!