Akka Typed testing - Expect message of type without knowing message details

452 Views Asked by At

Let's say I have an Actor (OrderGenerator) that in response to an incoming message (GenerateOrder), sends a message to another Actor (OrderProcessor) of type Order.

case class Order(orderId: String, partNumber: String, orderQty: Int) // ...etc.

In OrderGenerator's receiveMessage() method for the GenerateOrder message, we create an Order object. The orderId value is generated at this time (let's say it's a UUID generated on the fly). It then sends this Order as a message to the OrderProcessor Actor.

  Behaviors.receiveMessage {
    case GenerateOrder(partNumber: String, orderQty: Int) =>
      val newOrder = Order(orderId=GenerateUUID(), partNumber=partNumber, orderQty=orderQty)
      orderProcessor ! newOrder
      Behaviors.same

Ok, now I want to test this.

val inbox = TestInbox[Order]()
val TestKit = BehaviorTestKit(OrderGenerator(orderProcessor=inbox.ref))
testKit.run(GenerateOrder(partNo="widgetX", orderQty=5))
inbox.expectMessage(Order( ??????? ))

As you can see, I don't know what the full details are of the expected Order, since the orderId is generated by OrderGenerator at runtime, and I can't predict what the UUID will be.

How can I test that an Order message is sent, without knowing what the details will be (or only some of them)?

1

There are 1 best solutions below

0
On BEST ANSWER

I know this might sound kind of an "unsafe approach" (I don't think there's any other choice though), but just took a look at docs of akka TestInbox, you can use these 2 methods and use other fields of your order as assertions:

assert(inbox.hasMessages())
val message = inbox.receiveMessage()
assert(message.isInstanceOf[Order]) // or essentially any other comparison, like message.partNo == "widgetX"