如何模拟子Actor以测试Akka系统?

编程入门 行业动态 更新时间:2024-10-09 09:14:58
本文介绍了如何模拟子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系统?

本文发布于:2023-11-25 06:29:20,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628674.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试   系统   Actor   Akka

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!