如何模拟子Actor以测试Akka系统? [英] How to mock child Actors for testing an Akka system?

查看:84
本文介绍了如何模拟子Actor以测试Akka系统?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Akka中有一个父演员时,它会在初始化时直接创建一个子演员,当我想为父演员编写单元测试时,如何用TestProbe或模拟代替子演员?

When I have a parent actor in Akka, that directly creates a child actor on initialisation, when I want to write unit tests for the parent actor, how can I replace the child actor with a TestProbe or a mock?

例如,使用以下伪代码示例:

For example, with the following contrived code sample:

class TopActor extends Actor {
  val anotherActor = context.actorOf(AnotherActor.props, "anotherActor")

  override def receive: Receive = {
    case "call another actor" => anotherActor ! "hello"
  }
}

class AnotherActor extends Actor {

  override def recieve: Receive = {
    case "hello" => // do some stuff
  }

}

如果我要为TopActor编写测试,以检查发送给AnotherActor的消息是否为 hello,我如何替换执行AnotherActor?似乎TopActor是直接创建此子级的,因此访问起来并不容易。

If I want to write a test for TopActor, to check the message sent to AnotherActor is "hello", how do I replace the implementation of AnotherActor? It seems like TopActor creates this child directly so this is not easy to access.

推荐答案

以下方法似乎可行,但可以覆盖另一个演员的val直接看起来有点粗糙。我想知道是否还有其他更清洁/推荐的解决方案,这就是为什么即使我有这个有效答案,我仍然问这个问题的原因:

The following approach seems to work but overriding the val of anotherActor directly seems a little crude. I was wondering if there were any other cleaner/ recommended solutions, which is why I still asked the question even though I have this working answer:

class TopActorSpec extends MyActorTestSuiteTrait {
  it should "say hello to AnotherActor when receive 'call another actor'" {
    val testProbe = TestProbe()

    val testTopActor = TestActorRef(Props(new TopActor {
      override val anotherActor = testProbe.ref
    }))

    testTopActor ! "call another actor"
    testProbe.expectMsg(500 millis, "hello")
  }
}

这篇关于如何模拟子Actor以测试Akka系统?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆