如何 link 对目标 actor 进行测试
how to link test probe with target actor
在 scala 中,创建一个探针然后 link 它与一个 actor 进行测试是非常方便的。
val probe = TestProbe()
val child = system.actorOf(Props(classOf[DependentChild], probe.ref))
从现在开始,发送到 child 的任何内容都可以在探测中收到。
在Java中没有这样的API。简单地让 probe
watch on actor 不会让它接收到到达 actor 的所有消息。
Java API 中的等价物是什么?
我使用以下 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");
最近已经添加了 issue created for adding such a forwarding actor. Note that one such helper actor。所以如果你愿意创建一个 PR,非常欢迎你。 :)
在 scala 中,创建一个探针然后 link 它与一个 actor 进行测试是非常方便的。
val probe = TestProbe()
val child = system.actorOf(Props(classOf[DependentChild], probe.ref))
从现在开始,发送到 child 的任何内容都可以在探测中收到。
在Java中没有这样的API。简单地让 probe
watch on actor 不会让它接收到到达 actor 的所有消息。
Java API 中的等价物是什么?
我使用以下 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");
最近已经添加了 issue created for adding such a forwarding actor. Note that one such helper actor。所以如果你愿意创建一个 PR,非常欢迎你。 :)