2

We are developing an application with Scala and Websockets. For the latter we use Java-Websocket. The application itself works great and we are in the middle of writing unit tests.

We use a WebSocket class as follows

class WebSocket(uri : URI) extends WebSocketClient(uri) {
  connectBlocking()
  var response = ""

  def onOpen(handshakedata : ServerHandshake) {
    println("onOpen")
  }
  def onMessage(message : String) {
    println("Received: " + message)
    response = message
  }
  def onClose(code : Int, reason : String, remote : Boolean) {
    println("onClose")
  }
  def onError(ex : Exception) {
    println("onError")
  }
}

A test might look like this (pseudo code)

websocketTest {
    ws = new WebSocket("ws://example.org")
    ws.send("foo")
    res = ws.getResponse()
    ....
}

Sending and receiving data works. However, the problem is that connecting to the websocket creates a new thread and only the new thread will have access to response using the onMessage handler. What is the best way to either make the websocket implementation single-threaded or connect the two threads so that we can access the response in the test case? Or is there another, even better way of doing it? In the end we should be able to somehow test the response of the websocket.

str
  • 42,689
  • 17
  • 109
  • 127

1 Answers1

0

There are a number of ways you could try to do this. The issue will be that you might get an error or a successful response from the server. As a result, the best way is probably to use some sort of timeout. In the past I have used a pattern like (note, this is untested code):

...
use response in the onMessage like you did
...

long start = System.currentTimeMillis();
long timeout = 5000;//5 seconds

while((system.currentTimeMillis()-start)<timeout && response==null)
{
    Thread.sleep(100);
}

if(response == null) .. timed out
else .. do something with the response

If you want to be especially safe you can use an AtomicReference for the response.

Of course the timeout and sleep can be minimized based on your test case.

Moreover, you can wrap this in a utility method.

sasbury
  • 301
  • 1
  • 4