在Akka中,如果我有一个父Actor,在初始化时直接创建了一个子Actor,当我想为父Actor编写单元测试时,如何使用一个TestProbe或模拟对象替换子Actor?
例如,以下是一个人为构造的代码示例:
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直接创建了这个子级,因此很难访问。
testTopActor.underlyingActor
将会同时拥有anotherActor
和TopActor.anotherActor
。如果你的anotherActor
在其构造函数或任何生命周期函数中没有执行任何操作,那么这可能是可以接受的。但是,如果在构造函数中有一些运行,例如网络/数据库连接(我知道这很糟糕,但只是为了说明问题),那么当你创建你的testTopActor
时就会有两个这样的操作正在运行。也许要注意这种情况。 - CrazyGreenHand