How to test that Akka actor was created in Scala

北慕城南 提交于 2019-11-30 12:46:22

Inject Props for the children (e.g. HeartBeatAcceptWorker.props) in the constructor of the parent HeartBeatPumpWorker. Pass any Props you want from the test. Let the parent instantiate the children via provided Props. Interact with the children. The last part is dependent on your data flow. For instance if the parent shields you from the children, but delegates messages to them, send the message to the parent. If children talk to each other use test probes or something similar.

The technique I'm currently using is to intercept actor creation and create TestProbes. In my actors I mix in a separate ActorMaker trait:

trait ActorMaker { this: Actor =>
  def makeActor(props: Props) = context.actorOf(props)
}

And use it in MyActor extends Actor with ActorMaker instead of context.actorOf.

For tests I have a TestProbeMaker that captures all created actors and their props:

trait TestProbeMaker { this: Actor =>
  val probes = ListBuffer.empty[(Props, TestProbe)]
  def makeActor(props: Props) = { val probe = TestProbe()
    probes += (props -> probe)
    probe.ref
  }
}

And I mix it in during tests

val actorUnderTest = TestActorRef(Props(new MyActor with TestProbeMaker))

That way I can assert exactly what actors are created. I can also use probe.expectMsg to assert that messages are sent to those created actors.

To access the probes use actorUnderTest.underlyingActor.asInstanceOf[TestProbeMaker]

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!