Testing Actors

The tests in the Hello World example illustrates use of the JUnit framework. The test coverage is not complete. It shows how to test actor code and provides some basic concepts.

package $package$;

import akka.actor.testkit.typed.javadsl.TestKitJunitResource;
import akka.actor.testkit.typed.javadsl.TestProbe;
import akka.actor.typed.ActorRef;
import org.junit.ClassRule;
import org.junit.Test;

//#definition
public class AkkaQuickstartTest {

    @ClassRule
    public static final TestKitJunitResource testKit = new TestKitJunitResource();
//#definition

    //#test
    @Test
    public void testGreeterActorSendingOfGreeting() {
        TestProbe<Greeter.Greeted> testProbe = testKit.createTestProbe();
        ActorRef<Greeter.Greet> underTest = testKit.spawn(Greeter.create(), "greeter");
        underTest.tell(new Greeter.Greet("Charles", testProbe.getRef()));
        testProbe.expectMessage(new Greeter.Greeted("Charles", underTest));
    }
    //#test
}

Test class definition

public class AkkaQuickstartTest {

    @ClassRule
    public static final TestKitJunitResource testKit = new TestKitJunitResource();

Support for JUnit is included by using the TestKitJunitResource JUnit rule. This automatically creates and cleans up an ActorTestKit. To see how to use the testkit directly see the full documentation.

Test methods

This test uses TestProbe to interrogate and verify the expected behavior. Let’s look at a source code snippet:

@Test
public void testGreeterActorSendingOfGreeting() {
    TestProbe<Greeter.Greeted> testProbe = testKit.createTestProbe();
    ActorRef<Greeter.Greet> underTest = testKit.spawn(Greeter.create(), "greeter");
    underTest.tell(new Greeter.Greet("Charles", testProbe.getRef()));
    testProbe.expectMessage(new Greeter.Greeted("Charles", underTest));
}

Once we have a reference to TestProbe we pass it to Greeter as part of the Greet message. We then verify that the Greeter responds that the greeting has taken place.

Full test code

And, here is the complete code:

package $package$;

import akka.actor.testkit.typed.javadsl.TestKitJunitResource;
import akka.actor.testkit.typed.javadsl.TestProbe;
import akka.actor.typed.ActorRef;
import org.junit.ClassRule;
import org.junit.Test;

//#definition
public class AkkaQuickstartTest {

    @ClassRule
    public static final TestKitJunitResource testKit = new TestKitJunitResource();
//#definition

    //#test
    @Test
    public void testGreeterActorSendingOfGreeting() {
        TestProbe<Greeter.Greeted> testProbe = testKit.createTestProbe();
        ActorRef<Greeter.Greet> underTest = testKit.spawn(Greeter.create(), "greeter");
        underTest.tell(new Greeter.Greet("Charles", testProbe.getRef()));
        testProbe.expectMessage(new Greeter.Greeted("Charles", underTest));
    }
    //#test
}

The example code just scratches the surface of the functionality available in ActorTestKit. A complete overview can be found here.