I'm testing an actor that uses an asnychronous future-based API. The actor uses the pipe pattern to send a message to itself when a future completes:
import akka.pattern.pipe
// ...
// somewhere in the actor's receive method
futureBasedApi.doSomething().pipeTo(self)
In my test I mock the API so I control future completion via promises. However, this is interleaved with other messages sent directly to the actor:
myActor ! Message("A")
promiseFromApiCall.success(Message("B"))
myActor ! Message("C")
Now I'm wondering how I can guarantee that the actor receives and processes message B between message A and C in my test because message B is actually sent in another thread, so I can't control the order in which the actor's mailbox receives the messages.
I thought about several possible solutions:
sleep after each message for a few milliseconds to make another order very unlikely
wait for the actor to acknowledge each message, although acknowledgement is only required for testing
send message B directly to the actor to simulate completion of the future and write a separate test that ensures that the pipe pattern is properly used (the test above would not fail if the actor would not pipe the result message to itself)
I don't really like either of these options but I tend to use the last one. Is there another better way I can enforce a certain message order in the tests?
Clarification: The question is not how to deal with the fact that messages might be received in random order in production. Controlling the order in the test is essential to make sure that the actor can actually deal with different message orders.