Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Akka (with Java) how can I verify that my actor under test is watching another actor?

I have the following actor for which I would like to create unit tests to verify the following behaviour:

  1. ListeningActor correctly registers itself to watch the listeningTo actor.
  2. 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);
        }
    }
}
like image 819
vegemite4me Avatar asked Dec 27 '22 22:12

vegemite4me


2 Answers

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());
    }
}
like image 138
vegemite4me Avatar answered May 11 '23 05:05

vegemite4me


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

like image 44
Jan-Terje Sørensen Avatar answered May 11 '23 04:05

Jan-Terje Sørensen