在阿卡书中演员的第三章中。它使用消息事件来测试静默演员的状态。
演员是这样的:
object SilentActorProtocol {
case class SilentMessage(data: String)
case class GetState(receiver: ActorRef)
}
class SilentActor extends Actor {
import SilentActorProtocol._
var internalState = Vector[String]()
def receive = {
case SilentMessage(data) =>
internalState = internalState :+ data
case GetState(receiver) => receiver ! internalState
}
}
测试代码如下:
"change internal state when it receives a message, multi" in {
import SilentActorProtocol._
val silentActor = system.actorOf(Props[SilentActor], "s3")
silentActor ! SilentMessage("whisper1")
silentActor ! SilentMessage("whisper2")
silentActor ! GetState(testActor)
expectMsg(Vector("whisper1", "whisper2"))
}
内部测试代码为何使用GetState获取上述SilentMessage
事件的结果。
为什么不直接使用slientActor.internalState
得到结果呢?
有些朋友似乎误导了我的问题。
使用该
internalState
变量会遇到并发问题,因此应该使用GetState
事件告诉actor来获取actor的内部状态,而不是internalState
直接使用。
我不知道为什么它应该遇到并发问题,为什么使用GetState
可以解决问题
slientActor.internalState
不能直接获取内部变量,不能理解,使用silentActor.underlyingActor.internalState
就可以得到它。所以对这个可怕的问题感到抱歉。
如果我正确理解了您的问题,答案是测试代码中的silentActor不是actor,而是ActorRef实例,因此它没有要引用的internalState变量。
如果要在ActorRef上针对特定变量和方法编写单元测试,则需要使用文档中所描述的底层Actor技术(及其注意事项)。(请参见有关TestActorRef的部分。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句