19

How can I test expected message with akka testkit if I don't know all message details? Can I use somehow underscore "_"?

Example I can test:

echoActor ! "hello world"
expectMsg("hello world")

Example i want to test

case class EchoWithRandom(msg: String, random: Int)

echoWithRandomActor ! "hi again"
expectMsg(EchoWithRandom("hi again", _))

The way i don't want to use:

echoWithRandomActor ! "hi again"
val msg = receiveOne(1.second)
msg match {
    case EchoWithRandom("hi again", _) => //ok
    case _ => fail("something wrong")
}
Przemek
  • 7,111
  • 3
  • 43
  • 52

1 Answers1

31

It doesn't look like you can do much about it, because expectMsg uses == behind the scenes.

You could try to use expectMsgPF, where PF comes from PartialFunction:

echoWithRandomActor ! "hi again"
expectMsgPF() {
  case EchoWithRandom("hi again", _) => ()
}

Update

In recent versions (2.5.x at the moment) you need a TestProbe.

You can also return an object from the expectMsgPF. It could be the object you are pattern matching against or parts of it. This way you can inspect it further after expectMsgPF returns successfully.

import akka.testkit.TestProbe

val probe = TestProbe()

echoWithRandomActor ! "hi again"

val expectedMessage = testProbe.expectMsgPF() { 
    // pattern matching only
    case ok@EchoWithRandom("hi again", _) => ok 
    // assertion and pattern matching at the same time
    case ok@EchoWithRandom("also acceptable", r) if r > 0 => ok
}

// more assertions and inspections on expectedMessage

See Akka Testing for more info.

Nader Ghanbari
  • 4,120
  • 1
  • 23
  • 26
Ionuț G. Stan
  • 176,118
  • 18
  • 189
  • 202
  • Where does the `ok@` syntax come from? – user6296589 Jun 09 '21 at 15:16
  • 1
    @user6296589 it's called a pattern binder. There are SO questions about it, such as this one: https://stackoverflow.com/questions/2359014/scala-operator/2359365. The language specification deals with it here: https://scala-lang.org/files/archive/spec/2.13/08-pattern-matching.html#pattern-binders – Ionuț G. Stan Jun 09 '21 at 16:30