Search code examples
scalaakkaakka-testkit

Akka Actor isTerminated deprecated


Just writing a unit test to ensure an actor shuts down under certain conditions, so I have a test like:

    val tddTestActor = TestActorRef[MyActor](Props(classOf[MyActor], "param1"))
    tddTestActor ! someMessage
    tddTestActor.isTerminated shouldBe true

I'm picking up a warning that isTerminated is deprecated. The hint recommends I use context.watch() however in a unit test I don't have a parent actor or any context to watch.

What would be the bext way to validate tddTestActor shuts down ?


Solution

  • I agree that watching is the best way to get this done. When I am testing for stop behavior, I will usually use a TestProbe as the watcher to check on my actor under test. Say I had a very simple Actor defined as follows:

    class ActorToTest extends Actor{
      def receive = {
        case "foo" => 
          sender() ! "bar"
          context stop self
      }
    }
    

    Then, using specs2 in combination with akka's TestKit I could test the stop behavior like so:

    class StopTest extends TestKit(ActorSystem()) with SpecificationLike with ImplicitSender{
    
      trait scoping extends Scope {
        val watcher = TestProbe()
        val actor = TestActorRef[ActorToTest]
        watcher.watch(actor)
      }
    
      "Sending the test actor a foo message" should{
        "respond with 'bar' and then stop" in new scoping{
          actor ! "foo"
          expectMsg("bar")
          watcher.expectTerminated(actor)
        }
      }
    
    }