当我在Akka中有一个父演员时,它会在初始化时直接创建一个子演员,当我想为父演员编写单元测试时,如何用TestProbe或模拟代替子演员?
例如,使用以下人为设计的代码示例:
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直接创建了这个孩子,所以这并不容易访问。
最佳答案
以下方法似乎有效,但直接覆盖anotherActor的值似乎有点粗糙。我想知道是否还有其他更清洁/推荐的解决方案,这就是为什么即使我有这个有效答案,我仍然问这个问题的原因:
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")
}
}