lundi 7 novembre 2016

Play! scala and Akka: how to test if an actor A send a message to an actor B (using Play factories)?

I want to test that an actor A send well a message to an actor B after have received a message.

I'm using Play! 2.5 and I use the factories since I need to inject some classes inside my actors.

The Actor A looks like:

object ActorA {
  trait Factory {
    def apply(ec: ExecutionContext, actorBRef: ActorRef): Actor
  }
}

class ActorA @Inject()(implicit val ec: ExecutionContext,
                       @Named("actor-b") actorBRef: ActorRef)
    extends Actor with ActorLogging with InjectedActorSupport {

  override def receive: Receive = {
    case i: Long =>
      log info s"received $i"
      actorBRef ! (i+1)
}

And the actor B is even more simple: object ActorB { trait Factory { def apply(): Actor } }

class ActorB extends Actor with ActorLogging {

  override def receive: Receive = {
    case _ =>
      log error "B received an unhandled message"
  }
}

But my test doesn't pass, it is said that the expected message doesn't arrive, I get a Timeout in the test (but it is well logged by the actor B) so the problem come from my test (and probably the Probe).

Here is the test:

  val actorBProbe = TestProbe()
  lazy val appBuilder = new GuiceApplicationBuilder().in(Mode.Test)
  lazy val injector = appBuilder.injector()
  lazy val factory = injector.instanceOf[ActorA.Factory]
  lazy val ec = scala.concurrent.ExecutionContext.Implicits.global
  lazy val factoryProps = Props(factory(ec, actorBProbe.ref))
  val ActorARef = TestActorRef[ActorA](factoryProps)

  "Actor B" must {

    "received a message from actor A" in {
      ActorARef ! 5L

      actorBProbe.expectMsg(6L)
    }
  }

I also created a minimum Play! application with the code above available here.

Aucun commentaire:

Enregistrer un commentaire