Akka Java是否使用路径创建测试探针引用?

2vuwiymt  于 2022-11-06  发布在  Java
关注(0)|答案(1)|浏览(105)

我对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,创建一个带有相关路径的测试引用,但是我不确定如何做到这一点?如果有一种替代方法更适合测试这种交互,我也渴望了解它。

tsm1rwdh

tsm1rwdh1#

我用来解决这个问题的模式包括创建一个转发参与者,如下所示:


**

 * 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)结合使用来解决此问题。
我通过这个博客发现了上述技术:http://geekswithblogs.net/johnsPerfBlog/archive/2014/01/02/akka-test-patterns-for-java.aspx

相关问题