简体   繁体   English

测试传出的Akka Actor消息

[英]Testing Outgoing Akka Actor Messages

Let's say I have an actor like this (Using Akka 2.1 with Scala 2.10): 假设我有一个这样的演员(在Scala 2.10中使用Akka 2.1):

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. 因此,现在客户端收到连接消息时,它将其发送到ConfigurationManager并进入另一种状态。 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. 我不能在这里期望Msg()左右,因为它将被发送到其他角色。 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. 也许您应该只相信Akka内部的消息发送机制能​​够像宣传的那样工作。 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. 如果您真的不敢相信这一点,那么最好的解决方案是下载Akka源代码,然后添加自己的单元测试以涵盖您的用例,或者修改代码以支持自己的单元测试需求。

Or you could use something like Camel to do all the message sending and intercept messages that way. 或者,您可以使用诸如Camel之类的方式来执行所有消息发送和拦截消息。

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. 这种情况与测试普通对象之间的协作非常相似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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