如何将测试探针与目标actor相关联

时间:2015-03-19 04:10:43

标签: java akka

在scala中,创建探针然后将其与actor进行链接以进行测试非常方便。

val probe = TestProbe()
val child = system.actorOf(Props(classOf[DependentChild], probe.ref))

从那时起,无论发送给孩子的是什么,都可以在探测中得到预期。

在Java中,没有这样的API。简单地让probe监视演员不会让它收到所有到达演员的消息。

Java API中的等价物是什么?

2 个答案:

答案 0 :(得分:0)

我使用以下ForwardingActor来提供此功能(请参阅原始方法源的注释):

/**
 * Simple actor that takes another actor and forwards all messages to it.
 * Useful in unit testing for capturing and testing if a message was received.
 * Simply pass in an Akka JavaTestKit probe into the constructor, and all messages
 * that are sent to this actor are forwarded to the JavaTestKit probe
 * Ref: https://gist.github.com/jconwell/8153535
 */
public class ForwardingActor extends UntypedActor {
    LoggingAdapter LOG = Logging.getLogger(getContext().system(), this);
    final ActorRef target;
    public ForwardingActor(ActorRef target) {
        this.target = target;
    }
    @Override
    public void onReceive(Object msg) {
        LOG.debug("{}", msg);
        target.forward(msg, getContext());
    }
}

并使用它:

JavaTestKit actor1Probe = new JavaTestKit(actorSystem);
actorSystem.actorOf(Props.create(ForwardingActor.class, actor1Probe.getRef()), "actor1");

答案 1 :(得分:0)

已经有一个issue created用于添加这样的转发actor。请注意,最近添加了一个such helper actor。因此,如果您愿意创建公关,我们非常欢迎您。 :)