1
votes

First of all, I am not asking how to unit test an Akka Actor. I know the techniques to do that. My problem is slightly different.

I am developing a Scala program, let's call it the client, that does not use Akka Actors. However, the program uses a library, let's call it the server, whose interface is implemented using an Akka Actor.

Then, through the ask pattern, the client interacts with the server.

// This is the client program
class Client(uri: String) {
  implicit val context: ActorSystem = ActorSystem("client-actor-system")
  private val mainActor = context.actorSelection(uri)

  def connect: Future[SomeClass] = {
    implicit val timeout: Timeout = Timeout(5 seconds)
    (mainActor ? Connect()).mapTo[CreationResponse]
  }
}

Now, I want to write down some unit tests for Client class. Unit testing means to test a class in isolation. Every external dependency should be mocked.

How can I mock the reference to mainActor inside Client class? How can I inject in the actor system a mock actor for mainActor?

Thanks in advance.

1

1 Answers

2
votes

I would inject the mainActor actor selection into the client, and create that using Akka TestKits.

Of course, you need an ActorSelection, not an ActorRef. Some solutions for that can be found here:

Giving an ActorPath for a testProbe

Or alternatively, you could make mainActor an ActorRef by sending an Identify message to the ActorSelection.