0

I have a method which connects to a websocket and gets stream messages from some really outside system.

The simplified version is:

def watchOrders(): Var[Option[Order]] = {
  val value = Var[Option[Order]](None)
  // onMessage( order => value.update(Some(order))
  value
}

When I test it (with scalatest), I want to make it connect to the real outside system, and only check the first 4 orders:

test("watchOrders") {
  var result = List.empty[Order]
  val stream = client.watchOrders()
  stream.foreach {
    case Some(order) =>
      result = depth :: result
      if (result.size == 4) {      // 1. 
        assert(orders should ...)  // 2. 
        stream.kill()              // 3. 
      }
    case _ => 
  }
  Thread.sleep(10000)              // 4. 
}

I have 4 questions:

  1. Is it the right way to check the first 4 orders? there is no take(4) method found in scala.rx
  2. If the assert fails, the test still passes, how to fix it?
  3. Is it the right way to stop the stream?
  4. If the thread doesn't sleep here, the test will pass the code in case Some(order) never runs. Is there a better way to wait?
Freewind
  • 193,756
  • 157
  • 432
  • 708

1 Answers1

1

One approach you might consider to get a List out of a Var is to use the .fold combinator.

The other issue you have is dealing with the asynchronous nature of the data - assuming you really want to talk to this outside real world system in your test code (ie, this is closer to the integration test side of things), you are going to want to look at scalatest's support for async tests and will probably do something like construct a future out of a promise that you can complete when you accumulate the 4 elements in your list.

See: http://www.scalatest.org/user_guide/async_testing

Voltaire
  • 76
  • 4