简体   繁体   中英

Mock Child Actors Akka Java with Specific Ids

I am working with Akka 2.5.23 . I have a parent actor that forwards a Register Message to a child and the child replies to the original sender with an Initialized message .

I am facing some tough time unit testing this code flow. I am trying to externalize child creation for the parent but cannot seem to figure out how to pass define the name of the child actor while creating the child actor

Below is my ParentActor

public class ParentActor extends AbstractLoggingActor {

    private final Function<ActorRefFactory, ActorRef> childMaker;

    public ParentActor() {
        this.childMaker = arg -> {
            return context().actorOf(ChildActor.props("ID", appContext), "ACTOR_NAME");
        };
    }

    private void handleRegisterMessage(RegisterMessage message){

        childMaker.apply(context());

        // what I generally do:
        // context().actorOf(ChildActor.props(message.getUniqueId(), "TransChild-" + message.getUniqueId());

    }
}

Below is my ChildActor :

public class ChildActor extends AbstractLoggingActor {

    private final String uniqueId;

    public ChildActor(String uniqueId){
        this.uniqueId = uniqueId;
    }

    public static Props props(String uniqueId) {
        return Props.create(ChildActor.class, uniqueId);
    }
}

Can anyone help me with this?

he Ids are generated based on input message. The parent creates a child actor with a specific id (derived from message). That unique ID is passed to the child via Props and the child on PreStart() performs operations based on the passed uniqueId via Props

Not entirely sure I understand which part is the problem, but, you could:

Make the "childMaker" a BiFunction<String, ActorRefFactory, ActorRef> instead and create named children in the main one using `but return a probe or spawned test specific actor in the test.

So instead of f -> f.actorOf(Props.create(Child.class)) you'd do (name, f) -> f.actorOf(props, name)

To be honest I'd probably not use a lambda but define a protected ActorRef spawnChild(RegisterMessage message) method in the Actor class in Java instead and override that in the test. Will probably be more clear, not sure why we have such an example in the docs.

You can either use a counter and append at the end of the actor name you want to give to that actor. Like,

public ParentActor() {
        int counter = 0;
        this.childMaker = arg -> {
            return context().actorOf(ChildActor.props("ID", appContext), "ACTOR_NAME" + counter++);
        };
    }

You cannot create multiple actors of the same name. For more information about actor creation, you can read this .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM