Skip to content

Testing

actor4j-testing tests the behavior of an actor from the outside (black box testing): how does the actor react to an incoming message? A special actor system, the TestSystem, intercepts the outgoing messages of the actor under test, so that a test can await and check them.

Each actor to be tested implements the interface ActorTest. Its method test() returns a list of stories. A story consists of scenarios with given, when and then steps, as known from behavior-driven development (BDD). The TestSystem executes the stories of the actors.

TestSystem is an ActorSystem of Actor4j - Core. It is based on the default runtime (actor4j-core-runtime) and replaces its message dispatcher with one that redirects the messages of the actor under test. The actors themselves stay unchanged: they are ordinary actors of the SDK that additionally implement ActorTest. The assertions are based on JUnit 4, which comes with the module (junit-vintage-engine).

<dependency>
<groupId>io.actor4j</groupId>
<artifactId>actor4j-testing</artifactId>
<version>2.5.0</version>
<scope>test</scope>
</dependency>

The following story sends the message “Hello World!” to the actor itself. The actor answers with “Hello World Again!” to the sender. The TestSystem intercepts this answer, and the story checks it.

public class MyActor extends Actor implements ActorTest {
@Override
public void receive(ActorMessage<?> message) {
if (message.value() instanceof String) {
logger().info(String.format(
"Received String message: %s", message.valueAsString()));
tell("Hello World Again!", 0, message.source());
}
else
unhandled(message);
}
@Override
public List<Story> test() {
TestSystem system = (TestSystem)getSystem();
AtomicReference<String> actual = new AtomicReference<>();
Story story = new Story();
story.scenario()
.annotate("Scenario: Sending and receiving a message String")
.annotate("Given a request message")
.given(() -> send(ActorMessage.create("Hello World!", 0, system.SYSTEM_ID(), self())))
.annotate("When the responded message was received")
.when(() -> {
try {
actual.set(system.awaitMessage(5, TimeUnit.SECONDS).valueAsString());
} catch (InterruptedException | TimeoutException e) {
throw new AssertionError("No response", e);
}
})
.annotate("Then the responded received String message will be \"Hello World Again!\"")
.then(() -> outcome(actual.get()).shouldBe("Hello World Again!"))
.and(() -> system.assertNoMessages(200, TimeUnit.MILLISECONDS));
return List.of(story);
}
}

outcome is a static import from io.actor4j.bdd.OutcomeFactory. The texts of annotate are printed while the story runs.

The stories are executed within a JUnit test:

public class MyActorFeature {
protected TestSystem system;
@Before
public void before() {
system = TestSystem.create();
}
@After
public void after() {
system.shutdownWithActors(true);
}
@Test(timeout=5000)
public void test() {
system.addActor(() -> new MyActor());
system.start();
system.testAllActors();
}
}

testAllActors() executes the stories of every actor that implements ActorTest, one actor after the other. testActor(id) executes only the stories of one actor. A failing step fails the JUnit test. All stories are still executed. The first failure is thrown, further failures are attached as suppressed exceptions. A TestSystemConfig can be passed to TestSystem.create(...), e.g. TestSystemConfig.builder().parallelism(2).build().

Element Meaning
Story a list of scenarios, created with story.scenario()
Scenario steps added with given, when, then and and, executed in this order. annotate(text) adds a descriptive line.
Step a functional interface (void step()), usually a lambda
outcome(actual) checks a value: shouldBe, shouldNotBe, shouldBeTrue, shouldBeFalse, shouldBeNull, shouldBeNotNull, shouldBe(expected, delta) for double
Scenario.ensureThrows(step, exceptionClass) a step that expects the given exception

A scenario can also be run with several examples: scenario.example(...) adds input values and .captured(...) the expected values. Inside the steps, Scenario.example() and Scenario.captured() return the values of the current run.

While an actor is under test, every message it sends to another actor is redirected to an internal pseudo actor. The steps fetch these messages with awaitMessage(timeout, unit), in the order they were sent.

  • Intercepted: tell and send by id or alias, priority, unsafe sends. In short, everything the actor under test sends to someone else.
  • Delivered as usual: messages to the actor under test itself (e.g. the request in the example, sent from SYSTEM_ID), all messages between other actors, and directives such as STOP or RESTART, also when the actor under test triggers them. So the supervision of its children keeps working.
  • An alias send of the actor under test to its own alias is intercepted as well.

The redirection ends as soon as the stories of the actor are finished, also when a step throws.

Method Meaning Use when
assertNoMessages() snapshot: no message is there right now the last expected message was already awaited, so nothing can still be on its way, or at the start of a story
assertNoMessages(timeout, unit) no message arrives within the timeout you want to show that the actor does not answer, or does not send anything more

Neither method consumes a message. A message found by them can still be fetched with awaitMessage.

The stories are executed on the caller’s thread (the JUnit thread), not on the actor’s thread. This is necessary, because a step that awaits a response would otherwise block the actor itself. As a consequence, steps should send messages and check messages. They should not read or write fields of the actor directly, because the actor processes messages on its own thread at the same time. To check the internal state, let the actor answer a state query. The answer is intercepted like any other message:

public class CounterActor extends Actor implements ActorTest {
public static final int INCREMENT = 1;
public static final int STATE = 2;
protected long counter;
@Override
public void receive(ActorMessage<?> message) {
if (message.tag()==INCREMENT)
counter++;
else if (message.tag()==STATE)
tell(counter, STATE, message.source());
}
@Override
public List<Story> test() {
TestSystem system = (TestSystem)getSystem();
Story story = new Story();
story.scenario()
.given(() -> {
for (int i=0; i<3; i++)
send(ActorMessage.create(null, INCREMENT, system.SYSTEM_ID(), self()));
})
.when(() -> send(ActorMessage.create(null, STATE, system.SYSTEM_ID(), self())))
.then(() -> {
try {
outcome(system.awaitMessage(5, TimeUnit.SECONDS).value()).shouldBe(3L);
} catch (InterruptedException | TimeoutException e) {
throw new AssertionError("No state", e);
}
});
return List.of(story);
}
}

If a field must be read directly, declare it volatile or use an Atomic* type.

  • Scenario keeps the current example in static fields. Stories must therefore not be executed in parallel (e.g. parallel JUnit execution with several TestSystem instances in one JVM).
  • awaitMessage returns the next intercepted message. There is no filter by tag or sender yet.
  • The TestSystem is based on the default runtime. The other runtimes (classic, Loom, hybrid) are not covered by it.

Further examples can be found in the tests of the module under actor4j-testing.