by Raymond Roestenburg and Rob Bakker, authors of Akka in Action

Save 40% on Akka in Action and other selected books.

ScalaTest is a xUnit style testing framework. An actor is an object that can be reached through an address, processes messages from a mailbox and sends messages to other actors using the same type of addresses. An actor encapsulates state; it does not share this state with anyone. An actor has behavior, it does something specific with the messages it receives. This article, based on a portion of chapter 2 from Akka in Action, shows how to test actors and send one-way messages. Click here for 40% savings on Akka in Action and other related titles.


 

Testing actors is more difficult than testing normal objects for a couple of reasons:

  • Sending messages is asynchronous, so it is difficult to know when to assert expected values in the unit test.
  • Actors are meant to be run in parallel on several threads. Multi-threaded tests are more difficult than single-threaded tests and require concurrency primitives like locks, latches, and barriers to synchronize results from various actors. Exactly the kind of thing we wanted to get a bit further away from.
  • Incorrect usage of just one barrier can block a unit test which in turn halts the execution of a full test suite.
  • An actor hides its internal state and does not allow access to this state. Access should only be possible through the ActorRef. Calling a method on an actor and checking its state is prevented on purpose, which is something you would like to be able to do when unit testing.
  • If you want to do an integration test of a couple of actors, you would need to eavesdrop in between the actors to assert if the messages have the expected values. It