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")
}
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", _) => ()
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With