I have the following actor for which I would like to create unit tests to verify the following behaviour:
ListeningActor
correctly registers itself to watch the listeningTo
actor.ListeningActor
correctly kills itself when the listeningTo
actor terminates.How can I verify these two behaviours?
I am using Akka 2.0.2 with Java.
Thanks
public class ListeningActor extends UntypedActor {
private final ActorRef listeningTo;
public ListeningActor(final ActorRef listeningTo) {
this.listeningTo = listeningTo;
}
@Override
public void preStart() {
super.preStart();
context().watch(listeningTo); // <---- To verify
}
@Override
public void onReceive(final Object o) throws Exception {
if (o instanceof Terminated) {
Terminated terminated = (Terminated) o;
if (terminated.equals(listeningTo)) {
context().stop(self()); // <---- To verify
}
} else {
unhandled(o);
}
}
}
If it helps anyone, here's my final unit test:
public class ListeningActorTest
{
private TestKit testKit;
private TestActorRef<ListeningActor> listeningActor;
private TestProbe listeningToActor;
@Before
public void setUp() throws Exception
{
testKit = new TestKit(ActorSystem.apply());
listeningToActor = TestProbe.apply(testKit.system());
listeningActor = TestActorRef.apply(new Props(new UntypedActorFactory()
{
@Override
public Actor create()
{
return new ListeningActor(listeningToActor.ref());
}
}), testKit.system());
}
@Test
public void shouldTerminateWhenTheListeningToActorTerminates()
{
//Given
assertFalse(listeningActor.isTerminated());
//When
listeningToActor.testActor().tell(PoisonPill.getInstance());
//Then
assertTrue(listeningActor.isTerminated());
}
}
If you are using JavaTestKit and akka version 2.4.2 you could solve it like this:
@Test
public void testThatPersistenceActorShutdown() {
watch(persistenceActor);
persistenceActor.tell(new Shutdown(), getRef());
expectTerminated(persistenceActor);
}
You can find a working example here - akka-persistence-java-example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With