简体   繁体   中英

Testing Outgoing Akka Actor Messages

Let's say I have an actor like this (Using Akka 2.1 with Scala 2.10):

class ClientActor extends Actor with ActorLogging {

  val configurationManager = context.actorOf(Props[ConfigurationManager], "ConfigurationManager")

  def disconnected: Receive = {
    case msg: Connect => 
      configurationManager ! msg
      context.become(connecting)
  }

  ..

  def recieve = disconnected
}

So now when the Client receives a Connect message, it sends it to the ConfigurationManager and also goes into a different state. That's fine, but now I want to test this.

val clientRef = TestActorRef(new ClientActor).
clientRef ! new Connect
// ??

I can't expectMsg() or so here since it will be sent to a different actor. What is the best practice to handle such a situation? I just want to make sure that the message gets sent, but I dont know how to do this.

Thanks, Michael

Pass the dependency in as a constructor parameter:

Normal code:

val configActor = 
  system.actorOf(Props[ConfigurationManager], "configManager")

val clientActor = 
  system.actorOf(Props(new ClientActor(configActor)), "clientActor")

Test code:

val clientActor = 
  system.actorOf(Props(new ClientActor(testActor)), "clientActor")

Perhaps you should just trust that the message sending mechanisms inside Akka, work as advertised. If you really, really can't trust this, then the best solution is to download the Akka source code and either add your own unit tests to cover your use cases, or modify the code to support your own unit testing needs.

Or you could use something like Camel to do all the message sending and intercept messages that way.

If you abstract out the creation of the collaborating actor, then you can inject a test actor that does whatever you want. The situation is very similar to testing collaboration between ordinary objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM