gpt4 book ai didi

scala - 测试创建子 Actor 的 Actor

转载 作者:行者123 更新时间:2023-12-04 08:40:35 24 4
gpt4 key购买 nike

例如,我有两个 Actor ——一个父 Actor 和一个子 Actor 。当 parent 收到一条消息时,它会产生与消息中指定的一样多的子actor。如何测试此功能?有没有办法模拟上下文或其他方法来检查 Actor 是否正确创建且数量正确?

class ParentActor extends Actor {
case class CreateChildren(count: Int)

override def receive: Receive = {
case CreateChildren(count) => for (_ <- 0 until count) context.actorOf(Props[ChildActor])
}
}

class ChildActor extends Actor {
override def receive: Receive = {
case _ =>
}
}
更新:基于@Tim答案的解决方案
改变的类(class):
class ParentActor(childActorFactory: ChildActorFactory) extends Actor {
override def receive: Receive = {
case CreateChildren(count) => for (_ <- 0 until count) childActorFactory.create(context)
}
}

object ParentActor {
def props(childActorFactory: ChildActorFactory): Props = Props(new ParentActor(childActorFactory))
}

class ChildActorFactory {
def create(context: ActorContext): ActorRef = context.actorOf(Props[ChildActor])
}
测试:
"ParentActor" should {
"instantiate ten child actors" in {
val childrenCount = 10
val childActorFactory = mock[ChildActorFactory]
val parentActor = TestActorRef[ParentActor](ParentActor.props(childActorFactory))

parentActor ! CreateChildren(childrenCount)

Mockito.verify(childActorFactory, Mockito.times(childrenCount))
.create(parentActor.underlyingActor.context)
}
}

最佳答案

如果要完全测试父actor,则需要mock子actor,因此不能直接在父actor中创建子actor。相反,将工厂方法传递给父actor(依赖注入(inject)):

class ParentActor(makeChild: () => ChildActor) extends Actor {
case class CreateChildren(count: Int)

override def receive: Receive = {
case CreateChildren(count) => for (_ <- 0 until count) makeChild()
}
}
makeChild函数可以计算创建的actor的数量。它还可以返回 ChildActor 的模拟版本实现测试行为以强调 ParentActor .

关于scala - 测试创建子 Actor 的 Actor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64586310/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com