Akka Scala TestKit test PoisonPill message

1k views Asked by At

Given that I have a Supervisor actor which is injected with a child actor how do I send the child a PoisonPill message and test this using TestKit?

Here is my Superivisor.

class Supervisor(child: ActorRef) extends Actor {

  ...
  child ! "hello"
  child ! PoisonPill
}

here is my test code

val probe = TestProbe()
val supervisor = system.actorOf(Props(classOf[Supervisor], probe.ref))
probe.expectMsg("hello")
probe.expectMsg(PoisonPill)

The problem is that the PoisonPill message is not received. Possibly because the probe is terminated by the PoisonPill message?

The assertion fails with

java.lang.AssertionError: assertion failed: timeout (3 seconds) 
during expectMsg while waiting for PoisonPill
2

There are 2 answers

1
Governa On BEST ANSWER

I think this Testing Actor Systems should answer your question:

Watching Other Actors from Probes

A TestProbe can register itself for DeathWatch of any other actor:

val probe = TestProbe()
probe watch target
target ! PoisonPill
probe.expectTerminated(target)
0
Jörg Bächtiger On

In a test case, which extends the testkit, you can use the following code:

"receives ShutDown" must {
  "sends PosionPill to other actor" in {
    val other = TestProbe("Other")
    val testee = TestActorRef(new Testee(actor.ref))

    testee ! Testee.ShutDown

    watch(other.ref)
    expectTerminated(other.ref)
  }
}