Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching on testing expected message

Tags:

scala

akka

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")
}
like image 789
Przemek Avatar asked Aug 13 '14 13:08

Przemek


1 Answers

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.

like image 90
Ionuț G. Stan Avatar answered Oct 07 '22 23:10

Ionuț G. Stan