Testing Actors

The test in the Hello World example illustrates use of the ScalaTest framework. The test coverage is not complete. It simply shows how easy it is to test actor code and provides some basic concepts. You could add to it as an exercise to increase your own knowledge.

Test class definition

class AkkaQuickstartSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike {

Support for ScalaTest is included by extending ScalaTestWithActorTestKit. For other test frameworks the testkit can be used directly. See the full documentation.

This manages the lifecycle of the ActorTestKit we’ll use in the tests.

Test methods

This test uses TestProbe to interrogate and verify the expected behavior. Let’s look at a source code snippet:

"reply to greeted" in {
  val replyProbe = createTestProbe[Greeted]()
  val underTest = spawn(Greeter())
  underTest ! Greet("Santa", replyProbe.ref)
  replyProbe.expectMessage(Greeted("Santa", underTest.ref))
}

Once we have a reference to TestProbe we pass it to Greeter as part of the Greet message. We then verify that the Greeter responds that the greeting has taken place.

Full test code

And, here is the complete code:

package $package$

import akka.actor.testkit.typed.scaladsl.ScalaTestWithActorTestKit
import $package$.Greeter.Greet
import $package$.Greeter.Greeted
import org.scalatest.wordspec.AnyWordSpecLike

class AkkaQuickstartSpec extends ScalaTestWithActorTestKit with AnyWordSpecLike {

  "A Greeter" must {
    "reply to greeted" in {
      val replyProbe = createTestProbe[Greeted]()
      val underTest = spawn(Greeter())
      underTest ! Greet("Santa", replyProbe.ref)
      replyProbe.expectMessage(Greeted("Santa", underTest.ref))
    }
  }

}

The example code just scratches the surface of the functionality available in ActorTestKit. A complete overview can be found here.