我对使用akka进行测试还有点新意。在一个系统中,我正在做一些像
这样的事情private void tellPublisherAboutUpdates(Map<String,Update> updates){
if(updates.isEmpty()){
getContext().actorSelection(ActorSelectionPath.UPDATE_PUBLISHER.path()).tell(new InfoMessage<Map<String,Update>>(updates), getSelf());
}
}
现在,我首先想到的是,使用TestProbe创建一个带有相关路径的测试参考,但我不知道该怎么做?如果有一种更适合测试这种交互的替代方法,我也很想了解它。
答案 0 :(得分:2)
我用来解决这个问题的模式涉及创建如下的转发:
**
* 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 {
final ActorRef target;
public ForwardingActor(ActorRef target) {
this.target = target;
}
@Override
public void onReceive(Object msg) {
target.forward(msg, getContext());
}
}
然后您可以像这样使用它来注入探针参考:
JavaTestKit probe = new JavaTestKit(actorSystem);
actorSystem.actorOf(Props.create(ForwardingActor.class, probe.getRef()), "myActor");
当你希望你的actor成为当前actor或顶级actor的孩子时,这可以正常工作,但如果你的actor路径引用嵌套在层次结构中的actor,它可能有点棘手。我将ForwardingActor与ChildCreationActor(https://gist.github.com/jconwell/8154233)结合使用来解决这个问题。
我通过此博客了解了上述techqiue:http://geekswithblogs.net/johnsPerfBlog/archive/2014/01/02/akka-test-patterns-for-java.aspx