Desktop version

Home arrow Computer Science arrow Building Applications with Scala

Adding Akka tests

We will create three more tests: one for each actor that we have. They are located at


Scala test for Akka Actor

ChatUserActorSpec.scala should look something like this:

class OutActor extends Actor { def receive = {

case a:Any => Unit



class ChatUserActorSpec extends PlaySpec {

class Actors extends TestKit(ActorSystem("test"))

"ChatUserActor" should {

"joins the chat room and send a message" in new Actors { val probe1 = new TestProbe(system)

val actorOutRef = TestActorRef[OutActor](Props[OutActor]) val actorRef = TestActorRef[ChatUserActor] (ChatUserActor.props(system)(actorOutRef)) val userActor = actorRef.underlyingActor assert(userActor.context != null) val msg = "testUser:test msg" probe1.send(actorRef,msg) actorRef.receive(msg) receiveOne(2000 millis)




The Akka testkit is very cool as it allows us to test actors with a very easy Domain Specific Language (DSL). It's possible to check the Actor mailbox, the Actor internal state, and so much more. There is one trick that we will need to do because we need to extend one class; in order to have Play working with the Scala test, we will need to use PlaySpec. However, we will also need to extend one class to make the Akka testkit work, which is TestKit. We can't extend both at the same time, but no worries, there is always a workaround.

The workaround here is to create a case class, make that case class extend TestKit, and then use it in a spec context, that is, in a new Actor {}.

Here, we are checking if ChatUserActor can join the chat room properly. This is done by simply creating the Actor, as the Actor has a preStart method that will auto-join the room.

We will need to create a fake implementation of the out Actor here, which is why we have the OutActor implementation. We will create a probe to test the actor system, and we will also use a special function to test the Actors, called TestActorRef. This abstraction provides a way to access the Actor's state via actorRef.underlyingActor, and this is useful because you can check the Actor internal state to validate the code. The rest of the code is normal Akka and Scala test code. Let's move to the next test.

< Prev   CONTENTS   Source   Next >

Related topics