Skip to content

Instantly share code, notes, and snippets.

@johanandren
Created January 2, 2020 15:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johanandren/6f7891ad455f923f3fcae44fd94609a2 to your computer and use it in GitHub Desktop.
Save johanandren/6f7891ad455f923f3fcae44fd94609a2 to your computer and use it in GitHub Desktop.
Java mock actor child
class MyActor extends AbstractActor {
public Receive createReceive() {
return receiveBuilder()
.match(Request.class, this::onRequest)
.build();
}
private void onRequest(Request request) {
ActorRef child = createChildForRequest(request);
// do stuff with child, for example forward request
child.tell(request, getSender());
}
protected ActorRef createChildForRequest(Request request) {
return getContext().actorOf(Child.props(), request.getId());
}
}
class MyActorTest extends TestKit {
public MyActorTest() {
super(ActorSystem.create("MyActorTest"));
}
public void testSpawningChildOnRequest() {
TestProbe childCreationProbe = new TestProbe(getSystem());
ActorRef myActor = getSystem().actorOf(Props.create(() -> new MyActor() {
@Override
protected ActorRef createChildForRequest(Request request) {
TestProbe pretendChild = new TestProbe(getContext().getSystem());
childCreationProbe.ref().tell(pretendChild, ActorRef.noSender());
return pretendChild.ref();
}
}));
TestProbe senderProbe = new TestProbe(getSystem());
myActor.tell(new Request("id1"), senderProbe.ref());
TestProbe firstChildProbe = childCreationProbe.expectMsgClass(TestProbe.class);
Request firstRequest = firstChildProbe.expectMsgClass(Request.class);
assertEquals(firstRequest.getId(), "id1");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment