在scala中,创建一个探针,然后将其与一个actor链接进行测试是非常方便的。
val probe = TestProbe()
val child = system.actorOf(Props(classOf[DependentChild], probe.ref))
从那时起,发送给child的任何内容都可以在probe中预期。
在Java中,没有这样的API。简单地让probe
监视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");