我在我的游戏应用程序的WebSocket,我想编写一个测试它,但我找不到如何写这样一个测试的任何例子。 我发现在讨论游戏的框架,谷歌组,但一直没有任何活动最近。
那么,有没有关于如何测试的WebSocket的在Java测试任何想法?
我在我的游戏应用程序的WebSocket,我想编写一个测试它,但我找不到如何写这样一个测试的任何例子。 我发现在讨论游戏的框架,谷歌组,但一直没有任何活动最近。
那么,有没有关于如何测试的WebSocket的在Java测试任何想法?
您可以检索底层Iteratee,枚举并直接对其进行测试。 这样,您就不需要使用浏览器。 您需要阿卡 - testkit虽然,应付iteratees的异步特性。
Scala的例子:
object WebSocket extends Controller {
def websocket = WebSocket.async[JsValue] { request =>
Future.successful(Iteratee.ignore[JsValue] -> Enumerator.apply[JsValue](Json.obj("type" -> "error")))
}
}
class WebSocketSpec extends PlaySpecification {
"WebSocket" should {
"respond with error packet" in new WithApplication {
val request = FakeRequest()
var message: JsValue = null
val iteratee = Iteratee.foreach[JsValue](chunk => message = chunk)(Akka.system.dispatcher)
Controller.websocket().f(request)(Enumerator.empty[JsValue],iteratee)
TestKit.awaitCond(message == Json.obj("type" -> "error"), 1 second)
}
}
}
我测试使用Firefox的WebSockets代码:
https://github.com/schleichardt/stackoverflow-answers/commit/13d5876791ef409e092e4a097f54247d851e17dc#L8R14
对于Java它的工作原理类似与“FIREFOX”更换“的HtmlUnit”: http://www.playframework.com/documentation/2.1.x/JavaFunctionalTest
Chrome浏览器提供了一个插件来测试的WebSocket服务。
编辑
因此,使用该插件(如下面图中所示),可以提供的WebSocket URL和请求的数据和发送消息给服务。 和消息日志显示,从客户端,也服务响应发送的消息。
假设你有一个返回未来[Itearatee [JsValue,单位],枚举[JsValue]你的控制器使用的WebSocket库
trait WSLib {
def connect: Future[Itearatee[JsValue, Unit], Enumerator[JsValue]]
}
你想测试这个库。
这里是你可以使用上下文:
trait WebSocketContext extends WithApplication {
val aSecond = FiniteDuration(1, TimeUnit.SECONDS)
case class Incoming(iteratee: Iteratee[JsValue, Unit]) {
def feed(message: JsValue) = {
iteratee.feed(Input.El(message))
}
def end(wait: Long = 100) = {
Thread.sleep(wait) //wait until all previous fed messages are handled
iteratee.feed(Input.EOF)
}
}
case class OutGoing(enum: Enumerator[JsValue]) {
val messages = enum(Iteratee.fold(List[JsValue]()) {
(l, jsValue) => jsValue :: l
}).flatMap(_.run)
def get: List[JsValue] = {
Await.result(messages, aSecond)
}
}
def wrapConnection(connection: => Future[Iteratee[JsValue, Unit], Enumerator[JsValue]]): (Incoming, OutGoing) = {
val (iteratee, enumerator) = Await.result(conn, aSecond)
(Incoming(iteratee), OutGoing(enumerator))
}
}
然后你的测试可以写成
"return all subscribers when asked for info" in new WebSocketContext {
val (incoming, outgoing) = wrapConnection(myWSLib.connect)
incoming.feed(JsObject("message" => "hello"))
incoming.end() //this closes the connection
val responseMessages = outgoing.get //you only call this "get" after the connection is closed
responseMessages.size must equalTo(1)
responseMessages must contain(JsObject("reply" => "Hey"))
}
传入表示从客户端来的消息,而传出表示从服务器发送的消息。 编写测试,从传入传入的邮件先饲料,然后关闭致电incoming.end的连接,然后你从outgoing.get方法传出消息的完整列表。