Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test WebSocket in PlayFramework

I have a WebSocket in my Play application and I want to write a test for it, but I couldn't find any example on how to write such a test. I found a discussion in the play-framework Google group but there has been no activity recently.

So, are there any ideas on how to test WebSocket's in a Java test?

like image 872
pangratz Avatar asked May 03 '13 08:05

pangratz


People also ask

How do I know if WebSocket is working?

You can check if a WebSocket is connected by doing either of the following: Specifying a function to the WebSocket. onopen event handler property, or; Using addEventListener to listen to the open event.


2 Answers

You can retrieve underlying Iteratee,Enumerator and test them directly. This way you don't need to use a browser. You need akka-testkit though, to cope with asynchronous nature of iteratees.

A Scala example:

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)
    }
  }
}
like image 147
tokarev Avatar answered Oct 09 '22 21:10

tokarev


I test WebSockets code using Firefox:

https://github.com/schleichardt/stackoverflow-answers/commit/13d5876791ef409e092e4a097f54247d851e17dc#L8R14

For Java it works similar replacing 'HTMLUNIT' with 'FIREFOX': http://www.playframework.com/documentation/2.1.x/JavaFunctionalTest

like image 27
Schleichardt Avatar answered Oct 09 '22 22:10

Schleichardt