在Akka演员上与mockito进行间谍活动

时间:2015-01-09 18:33:17

标签: akka mockito scalatest

我想监视我的actor实例,但不能简单地用new关键字创建。我想出了以下解决方案:

  val testActorSpy = spy(TestActorRef(new TestActor).underlyingActor)
  val testActorRef = TestActorRef(testActorSpy )

但这样我创造了一个不必要的演员。有没有更清洁的解决方案?

1 个答案:

答案 0 :(得分:0)

所以我对Akka Actor系统的理解是你应该通过属性做到这一点然后呢?

因此,通过道具创建演员,并且在测试时只是将间谍返回给演员。

因此,这应该给你一个结果:

val testActorRef = TestActorRef(spy(new TestActor))
val testActorSpy = testActorRef.underlyingActor

请注意,重新启动actor时,basActor会被销毁。所以嘲笑这可能不是最好的选择。

如果直接使用actor而不是通过系统,你也可以测试一些东西并绕过线程化的底层系统。

请参阅this(java下面的代码粘贴)。

static class MyActor extends UntypedActor {
  public void onReceive(Object o) throws Exception {
    if (o.equals("say42")) {
      getSender().tell(42, getSelf());
    } else if (o instanceof Exception) {
      throw (Exception) o;
    }
  }
  public boolean testMe() { return true; }
}

@Test
public void demonstrateTestActorRef() {
  final Props props = Props.create(MyActor.class);
  final TestActorRef<MyActor> ref = TestActorRef.create(system, props, "testA");
  final MyActor actor = ref.underlyingActor();
  assertTrue(actor.testMe());
}
相关问题