Akka actor testing

401 views Asked by At

Since I am currently writing Testcases for my Akka application (http://doc.akka.io/docs/akka/snapshot/scala/testing.html) I was wondering if there is a way to test the interface of an actor. What I mean with that, is that I 'd like to check if the receive method of a target actor handles a message A or no. Imagine the following scenario:

Actor A can handle message b and c. Actor B wants to send mesage b and a to actor A. To ensure that this works out nice, I would like to write a test case that ensures that actor A is processing messages a and b.

1

There are 1 answers

1
Rob Starling On BEST ANSWER

It depends on what you want to test.

Since the receive method is a PartialFunction, you can do isDefinedAt tests like so:

$ sbt test:console
scala> import akka.actor._
scala> import akka.testkit._
scala> class MyActor extends Actor {
         def receive = {
           case n: Long => println("Got %d".format(n))
           case s: String => println("Got %s".format(s))
         }
       }

scala> implicit val system = ActorSystem()
system: akka.actor.ActorSystem = akka://default

scala> val myActor = TestActorRef[MyActor]
myActor: akka.testkit.TestActorRef[MyActor] = TestActor[akka://default/user/$$a]

scala> val underlying = myActor.underlyingActor
underlying: MyActor = MyActor@365d7762

scala> underlying.receive.isDefinedAt(123L)
res0: Boolean = true

scala> underlying.receive.isDefinedAt("banana")
res1: Boolean = true

scala> underlying.receive.isDefinedAt(true)
res2: Boolean = false

scala> underlying.receive.isDefinedAt(123)
res3: Boolean = false

scala> underlying.receive.isDefinedAt(null)
res4: Boolean = false

scala> system.shutdown()