Skip to content

Instantly share code, notes, and snippets.

@jessitron
Created March 19, 2014 15:23
Show Gist options
  • Save jessitron/9644029 to your computer and use it in GitHub Desktop.
Save jessitron/9644029 to your computer and use it in GitHub Desktop.
Akka testing: it's a good idea to tell your actor system to leave a dead top-level actor dead. See: http://blog.jessitron.com/2014/03/testing-in-akka-sneaky-automatic.html
// In real life, it's great that stuff gets restarted when it fails.
// In testing, we'd rather know that it failed.
import akka.actor._
class DyingActor extends Actor {
def receive = { case "die" => throw new Exception("poo") }
}
// Default config, everything restarts automatically
val system = ActorSystem("ordinary")
val dyingActor = val system.actorOf(Props(new DyingActor))
dyingActor.isTerminated
// false
dyingActor ! "die"
dyingActor.isTerminated
// false -- no indication that the actor was restarted
// so let's configure one that won't restart it
import com.typesafe.config.ConfigFactory
val stoppingConfigStr = """ akka.actor.guardian-supervisor-strategy = "akka.actor.StoppingSupervisorStrategy" """
val stoppingConfig = ConfigFactory.parseString(stoppingConfigStr)
val tenderSystem = ActorSystem("sensitive", stoppingConfig)
val stayingDeadActor = tenderSystem.actorOf(Props(new DyingActor))
stayingDeadActor.isTerminated
// false
stayingDeadActor ! "die"
stayingDeadActor.isTerminated
// true -- this is something we can check in our tests
@viktorklang
Copy link

Great tip!

I'd recommend to avoid actorRef.isTerminated—it is not reliable (in the sense that the only guarantee is that when it returns true it will always return true after that)
The best solution is to use DeathWatch + TestKit's expectTerminated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment