Reputation: 1247
I am wondering what the canonical way is of testing whether an actor has stopped in akka. Here is an example of how I am currently doing; I'm worried I'm over complicating it.
import akka.actor.{Terminated, Actor, Props, ActorSystem}
import akka.testkit.TestProbe
class MyActor extends Actor {
import MyActor._
override def receive: Receive = {
case Stop => context.stop(self)
}
}
object MyActor {
def props = Props(new MyActor)
case object Stop
}
object MyActorSpec {
val system = ActorSystem()
val myActor = system.actorOf(MyActor.props)
val testProbe = TestProbe()
case object MyActorStopped
val watcher = system.actorOf(Props(new Actor {
context.watch(myActor)
override def receive: Actor.Receive = {
case Terminated(`myActor`) => testProbe.ref ! MyActorStopped
}
}))
myActor ! MyActor.Stop
testProbe.expectMsg(MyActorStopped)
}
Upvotes: 13
Views: 5218
Reputation: 15074
You can get rid of the separate watcher actor, and just watch the target actor directly from the testProbe
actor:
val testProbe = TestProbe()
testProbe watch myActor
myActor ! MyActor.Stop
testProbe.expectTerminated(myActor)
See here for the relevant section of the Akka testing docs.
Upvotes: 28