当我在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系统?
发布评论