Asynchronous testing

Synchronous testing is a good and deterministic way to test actor logic, but sometimes it is just not enough, for example, when testing specific aspects of communication between actors. Another example is having asynchronous code in the actor's behavior, for example, Feature or scheduler, which needs to be finished before test assertions can be executed.

One example of such a situation is the Baker actor. We expect it to check the Oven after some predefined time interval. Unfortunately, this interval is hardcoded, so there is no possibility of being able to override it in the test and we need to wait for the timer to trigger.

As part of the asynchronous testing toolkit, Akka provides a ManualTimer, which can be used to advance time in tests in a flexible manner. We'll use it to reliably test our Baker actor.

First, we need to provide an appropriate configuration for the manual timer. We do this by overriding the config method of the actor system which is represented by the ActorTestKit and define an instance of the time we'll use in our test:

override def config: Config = ManualTime.config
val manualTime: ManualTime = ManualTime()

Now, we can specify the testing logic:

"The baker should" should {
"bake cookies in batches" in {
val oven = TestProbe[Oven.Command]()
val manager = TestInbox[Manager.Command]()
val baker = spawn(Baker.idle(oven.ref))
baker ! BakeCookies(RawCookies(1), manager.ref)
oven.expectMessage(Oven.Put(1, baker))
val justBeforeDone = DefaultBakingTime - 1.millisecond
manualTime.expectNoMessageFor(justBeforeDone, oven)
manualTime.timePasses(DefaultBakingTime)
oven.expectMessage(Extract(baker))
}
}

In this scenario,  we create an oven and a manager using TestProbe (as opposed to the TestInbox we used before) and also a baker behavior using the spawn method of the ActorTestKit. We send a request to the baker and expect it to react appropriately by putting a single cookie into the oven.

Next, we can see that the baker waits for the cookies to be ready by checking that no messages are sent during this period of time. We're using the annual time here, and because of this, the check itself is done instantly. Finally, we manually advance the timer so that the baker needs to extract the cookies from the oven and verify that this has indeed happened, and that the oven received the Extract message as expected.

The application has been successfully tested; let's wait no more and run it!

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.7.131