Search code examples
scalaakkaactorakka-testkit

Test actors: receive exactly N messages


I'm testing an application with Akka actors. I'm using Test probes. I want to verify that the probe receives EXACTLY 10 messages of the same type. One solution could be to write 10 times:

probe.expectMsg(20 seconds, Done)

But I would prefer a more general solution (for example I'd test my application also for n=100). I also tried probe.receiveN(10, 20 seconds) but if I receive more than 10 elements the test doesn't fail. Instead I want it to fail in this case. Is there a solution?


Solution

  • From the Akka Documentation:

    expectMsgAllOf[T](d: Duration, obj: T*): Seq[T]
    

    A number of objects matching the size of the supplied object array must be received within the given time, and for each of the given objects there must exist at least one among the received ones which equals (compared with ==) it. The full sequence of received objects is returned.

    Then use expectNoMsg(d: Duration) to make sure there is exactly the number required.

    With your code:

    val numberOfMessages = 10
    probe.expectMsgAllOf(20 seconds, Array.fill(numberOfMessages)(Done))
    probe.expectNoMsg(20 seconds)