我的Play应用程序中有一个WebSocket,我想为其编写一个测试,但是我找不到如何编写这样一个测试的例子.我在
play-framework Google群组中发现了一个讨论,但最近没有任何活动.
那么,有没有关于如何在Java测试中测试WebSocket的想法?
解决方法
您可以检索底层Iteratee,枚举器并直接测试它们.这样就不需要使用浏览器了.你需要akka-testkit,以应对迭代的异步性质.
一个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)
- }
- }
- }