【问题标题】:How to test Akka actor that spawn child actors at runtime?如何测试在运行时产生子演员的 Akka 演员?
【发布时间】:2016-10-18 05:25:08
【问题描述】:

按照我的other question,我有一个 UDP 服务器参与者,如下所示:

class Listener(addr: InetSocketAddress) extends Actor {
  import context.system
  IO(Udp) ! Udp.Bind(self, addr)

  def spawnChild(remote): ActorRef = {
    //Check if child already exist
    context.actorOf(Props[Worker])
  }

  def receive = {
    case Udp.Bound(local) =>
      context.become(ready(sender()))
  }

  def ready(socket: ActorRef): Receive = {
    case Udp.Received(data, remote) =>
      val worker = spawnChild(remote)
      worker ! data // forward data directly to child
    case Udp.Unbind  => socket ! Udp.Unbind
    case Udp.Unbound => context.stop(self)
  }
}

我正在根据数据的发送位置创建子角色。这样做的原因是为了让子角色保持一些内部状态。内部状态包括上次连接时间、发送数据包总数等

我想设置 TestProbes 来测试它

  • remoteA 中的数据被转发到 TestProbeA
  • remoteB 中的数据被转发到 TestProbeB
  • remoteA 中的数据未转发到 TestProbeB

我已阅读Using multiple probes 部分。但是在我的情况下,负责创建孩子的是父母演员。

在这种情况下,我应该如何编写规范?或者,我应该如何重构我的代码以更适合测试?

【问题讨论】:

    标签: scala testing akka


    【解决方案1】:

    akka 文档中有一个部分概述了可以实现的几种方法:Testing parent child relationships

    在工作中,我们已经成功地使用了从父级外部化子生成中解释的方法。这实际上意味着您的父actor在初始化时(或通过消息)采用“子工厂”参数。

    在测试代码中,您可以提供一个“假”工厂,它将返回一个测试探针,而不是一个纯actor。

    【讨论】:

    • 感谢您的回答。我将阅读该部分并在此处发布我的发现。
    猜你喜欢
    • 2014-03-09
    • 2016-02-03
    • 2015-07-24
    • 1970-01-01
    • 2021-02-11
    • 2012-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多