我正在尝试编写一个测试,以验证下面的actor是否正在创建一个heartBeatExpireWorker和一个heartBeatAccepter,但我不知道如何做到这一点。
首先,我想我可以使用Mockhito mock或间谍来代替上下文,然后验证我是否调用了actorOf,但我无法找到一种在不破坏Akka测试框架的情况下注入上下文的方法。
然后,我想我可以向工人发送一条识别信息,以验证他们的存在。但我突然想到,这也不起作用,因为Akka TestKit似乎无法为测试中的演员创造儿童演员。它只能接收可以代替相邻参与者的Testprobes。
class HeartBeatPumpWorker(chatService: ChatService, target: HeartBeatMessageCmd) extends Actor with ActorLogging with
WorkersReference {
val heartBeatInterval = chatService.getHeartBeatInterval
val tick = context.system.scheduler.schedule(0 millis, heartBeatInterval millis, self, SendHeartBeat(target))
override def postStop() = tick.cancel()
def receive = {
case SendHeartBeat(command: HeartBeatMessageCmd) =>
log.debug("Sending heartbeat")
//Send heartbeat to GWT
val userTarget = NetworkWorker.buildEventUserTarget(command.getEventCode, command.getUser)
val uuid: String = UUID.randomUUID().toString
val freshCommand = new HeartBeatMessageCmd(command.getUser, command.getEventCode, uuid, command.getUserSession)
networkWorker ! NetworkBroadcast(userTarget, freshCommand)
val heartBeatId: String = freshCommand.getUuid
//create expirer
val heartBeatExpireWorkerRef = context.actorOf(HeartBeatExpireWorker.props(chatService, freshCommand),
HeartBeatExpireWorker.name(heartBeatId))
val heartBeatAccepterRef = context
.actorOf(HeartBeatAcceptWorker.props(chatService, freshCommand), HeartBeatAcceptWorker.name(heartBeatId))
//record heartbeat
chatService.saveSentHeartbeat(heartBeatId, freshCommand.getUserSession, freshCommand.getEventCode,
freshCommand.getUser,
freshCommand.getTimeCmdGenerated)
case _ =>
log.error("Pumper received unknown message. This shouldn't happen " + sender.path.toString)
self ! PoisonPill
}
}
object HeartBeatPumpWorker {
def name(eventCode: String, user: String, sessionId: String) = f"HeartBeatPumpWorker-$eventCode-$user-$sessionId"
def path(eventCode: String, user: String, sessionId: String) : String = {
EventWorker.Path + "/" + name(eventCode, user, sessionId)
}
def props(chatService: ChatService, heartBeatMsgCmd: HeartBeatMessageCmd) = {
Props(classOf[HeartBeatPumpWorker], chatService, heartBeatMsgCmd)
}
}
我目前使用的技术是拦截actor创建并创建TestProbes。在我的演员中,我融入了一个单独的演员制造者特质:
trait ActorMaker { this: Actor =>
def makeActor(props: Props) = context.actorOf(props)
}
并在MyActor extends Actor with ActorMaker
中使用它,而不是context.aactorOf.
对于测试,我有一个TestProbeMaker,它可以捕捉所有创建的演员及其道具:
trait TestProbeMaker { this: Actor =>
val probes = ListBuffer.empty[(Props, TestProbe)]
def makeActor(props: Props) = { val probe = TestProbe()
probes += (props -> probe)
probe.ref
}
}
我在测试时把它混合在一起
val actorUnderTest = TestActorRef(Props(new MyActor with TestProbeMaker))
通过这种方式,我可以断言确切地创建了哪些参与者。我还可以使用probe.expectMsg来断言消息已发送给那些创建的参与者。
要访问探测器,请使用actorUnderTest.underlyingActor.asInstanceOf[TestProbeMaker]
在父HeartBeatPumpWorker
的构造函数中为子级(例如HeartBeatAcceptWorker.props
)注入Props
。通过测试中想要的任何Props
。让父级通过提供的Props
实例化子级。与孩子们互动。最后一部分取决于您的数据流。例如,如果父级保护您不受子级的影响,但将消息委派给它们,则将消息发送给父级。如果孩子们互相交谈,使用测试探针或类似的东西。