Created
January 2, 2020 15:34
-
-
Save johanandren/6f7891ad455f923f3fcae44fd94609a2 to your computer and use it in GitHub Desktop.
Java mock actor child
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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