jor*_*nfb 6 guice akka playframework playframework-2.4
如何测试依赖注入创建的actor?在我的应用程序中,我可以通过命名注入获得ActorRef:
public MyClass {
@Inject
@Named("ping")
ActorRef mPingRef;
}
Run Code Online (Sandbox Code Playgroud)
如何在我的测试中获得此参考?
这是我的演员:
public class PingActor extends UntypedActor {
@Inject
public PingActor(Configuration configuration) {
... // Use config
}
@Override
public void onReceive(Object message) throws Exception {
if (message instanceof Ping) {
getSender().tell(new Pong(), getSelf());
}
}
public static class Ping {}
public static class Pong {}
}
Run Code Online (Sandbox Code Playgroud)
我已经使用自己的模块配置了我的应用程序:
public class MyModule extends AbstractModule implements AkkaGuiceSupport {
private final Configuration mConfig;
public MyModule(Environment environment, Configuration configuration){
this.mConfig = configuration;
}
@Override
protected void configure() {
bindActor(PingActor.class, "ping");
}
}
Run Code Online (Sandbox Code Playgroud)
该模块在application.conf中启用:
play.modules.enabled += "com.my.package.MyModule"
Run Code Online (Sandbox Code Playgroud)
该解决方案适用于PlayScala,但对于您的 ,它应该是相同的机制PlayJava:
所以我得到了我的GuiceModule:
class CommonModule extends AbstractModule with AkkaGuiceSupport {
override def configure(): Unit = {
bindActor[SomeActor]("actor-name")
}
}
Run Code Online (Sandbox Code Playgroud)
然后是测试(我从测试中删除了一些东西,所以它可能无法直接编译):
import akka.actor.{ActorRef, ActorSystem}
import akka.testkit.{TestKit, TestProbe}
import module.CommonModule
import org.specs2.mutable.Specification
import org.specs2.specification.Scope
import play.api.inject._
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.test.Helpers._
class SwitchUpdateActorSpec extends Specification {
"MyActor" should {
val actorSystem = ActorSystem("test")
class Actors extends TestKit(actorSystem) with Scope
val app = new GuiceApplicationBuilder(modules = Seq(new CommonModule))
.overrides(bind[ActorSystem].toInstance(actorSystem))
.build()
"respond with 'ok' upon receiving a message" in new Actors {
running(app) {
private val injector: Injector = app.injector
private val actor: ActorRef = injector.instanceOf(BindingKey(classOf[ActorRef]).qualifiedWith("actor-name"))
val probe = TestProbe()
actor.tell("hi there!", probe.ref)
probe.expectMsg("ok")
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以我所做的是:
ActorSystemactorSystem在 Akka 的TestKit( libraryDependencies += "com.typesafe.akka" %% "akka-testkit" % "2.4.1")中GuiceApplicationBuilder来应用覆盖app.injector直接使用 guice 配置的 actor 来访问当您查看方法bindActor中使用的实现时,很明显会发生什么MyModule.configure():
def bindActor[T <: Actor: ClassTag](name: String, props: Props => Props = identity): Unit = {
accessBinder.bind(classOf[ActorRef])
.annotatedWith(Names.named(name))
.toProvider(Providers.guicify(Akka.providerOf[T](name, props)))
.asEagerSingleton()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3023 次 |
| 最近记录: |