[Play 2.4 Scala] Testing with Guice and Akka

755 views
Skip to first unread message

Nelson Loyola

unread,
Jun 10, 2015, 3:57:07 PM6/10/15
to play-fr...@googlegroups.com

This page discusses how I can use Guice in my test code:

It shows how to get an instance of a component using injector.instanceOf. What I could not find though is information on injecting Akka actors.

How can I inject an instance of an Akka actor?

Thanks

Nelson Loyola

unread,
Jun 11, 2015, 2:17:12 PM6/11/15
to play-fr...@googlegroups.com

Rather than injecting actor instances, I’m now creating my actors using system.actorOf and passing the required parameters.

Andris Spruds

unread,
Jun 11, 2015, 4:13:41 PM6/11/15
to play-fr...@googlegroups.com
Hi Nelson,

See this link: https://www.playframework.com/documentation/2.4.x/ScalaAkka, look for "Dependency injecting actors". The only thing missing there is how to construct "TestActorRef" from injected actor. I haven't yet figured out that one.

Best regards,
Andris Spruds

Nelson Loyola

unread,
Jun 12, 2015, 5:39:33 PM6/12/15
to play-fr...@googlegroups.com

I figured out how to do it by looking at the Play code.

First you define your actor in a Guice module:

package modules

import com.google.inject.AbstractModule
import play.api.libs.concurrent.AkkaGuiceSupport

class AkkaModule extends AbstractModule with AkkaGuiceSupport {
  def configure() = {

    bindActor[MyAkkaActor]("myAkkaActor")
  }
}

And add this module to your application.conf:

...
play.modules.enabled += "modules.AkkaModule"
...

Then in your test suite you declare a case class that has an actor injected into it:

import javax.inject.{ Inject, Named }

case class MyNamedAkkaActor @Inject() (@Named("myAkkaActor") actor: ActorRef)

Then inject the ActorRef into a variable:

import play.api.inject.guice.GuiceApplicationBuilder

val app = new GuiceApplicationBuilder().build

val myActor = app.injector.instanceOf[MyNamedAkkaActor].actor

Then you can send messages to the actor myActor in your test cases.

Ritesh Jha

unread,
Oct 4, 2015, 2:45:40 PM10/4/15
to play-framework
can u share ur full code. plz.

Nelson Loyola

unread,
Oct 4, 2015, 3:02:52 PM10/4/15
to play-framework
You can have a look at line 116 of this file:


I'm not sure how much help it will be since this code is more complicated than my explanation above.

Nelson

Ritesh Jha

unread,
Oct 5, 2015, 2:09:29 AM10/5/15
to play-framework
Thanks a lot Nelson. I managed to run actor test. 
Reply all
Reply to author
Forward
0 new messages