Testing Groovy Actors

One thing I did not quite get when I was looking at multithreading technologies was how to unit test them.

I have not looked at Akka for a while, but a few years ago it seemed like the consensus was to use a logger like Log4J, and then parse the logging messages. That is kind of unwieldy and feels wrong. (Akka seems to have more ways to test now.)

I emailed the GPars list about putting private fields in an actor, changing them in the onMessage method, and then checking them afterwards; something like this:

class BadActor extends DynamicDispatchActor {
    private def someField
    private def someOtherField
    void onMessage( ObjectType message ) {
        someField = message.doStuff()
        someOtherField = message.doOtherStuff()

You could do that. There is nothing wrong with having private fields in an actor. You might want to keep some data between requests (like an encryption key). But making a field just for testing seems wrong.

Then I had an idea: Have your actor call another class that does the actual work, and unit test the worker class:

class BetterActor extends DynamicDispatchActor {
    void onMessage( BetterObjectType message ) {
        def worker = new WorkerClass( message )
        def result = worker.doWork()

I suppose that will not help with functional testing. It might violate some SOLID principle, or DRY, or GRASP or the Law of Demeter or Principle of Least Astonishment or Poe’s Law, but it seems like a pretty good idea to me.

You’re welcome.

Image from the “Imperial Menologion“, an 11th-century Byzantine manuscript, not to be confused with the Menologion of Basil II. Manuscript  housed at The Walters Art Museum, manuscript information here, image from World Document Library, image assumed allowed under Fair Use.