Saturday, July 12, 2014

Akka testing parrent child relation

Testing child actors is not piece of cake in Akka. Its because this actors often communicate with parent using context.parrent
context.parrent ! FOOMsg("foo")
One of possible and reusable solution is to create:
import akka.testkit.{TestProbe, TestKit}
import org.scalatest.Suite
import akka.actor.{Actor, Props, ActorSystem}

trait TestParentChildRelation {
  this: TestKit with Suite =>
  def mockParentWithProbe(childProps: Props)
                     (implicit system: ActorSystem) = {
    val proxy = TestProbe()
    system.actorOf(Props(new Actor {
      val child = context.actorOf(childProps)
      def receive = {
        case x if sender == child => proxy.ref forward x
        case x => child forward x
      }
    }))
    proxy
  }
}
The trait can be mixed into test scenario like in example from (Link)
class ProcreatorActorTest 
extends TestKit(ActorSystem("ProcreatorTestActorSystem"))
with ImplicitSender
with WordSpecLike
with StopSystemAfterAll
with TestParentChildRelation {

  "A Procreator actor" must {
    "recombine the genome" in {
      val maleGenotype = SampleGenome(Seq(1, 3, 3, 7, 1))
      val femaleGenotype = SampleGenome(Seq(9, 8, 7, 6, 5))

      val male = TestActorRef(new Phenotype(maleGenotype))
      val female = TestActorRef(new Phenotype(femaleGenotype))
      val proxy = mockParentWithProbe(Props(
             new TestRecombineProcreator(male, female, 1.0)))

      val expectedGenome = SampleGenome(Seq(1, 3, 7, 6, 5))
      proxy.expectMsg(Descendant(expectedGenome))
    }
}
Examples come from https://github.com/ppiotrow/scalagen project. I'm waiting for your feedback

No comments:

Post a Comment