在我的情況我有2個演員:阿卡:測試監控死看
watchee
(我用TestProbe
)watcher
(Watcher
包裹成TestActorRef
暴露了一些內部state
我跟蹤我的測試)
當watchee
去世時,看守應採取一些措施。
下面是完整的測試情況下,我到目前爲止已經寫的:
class TempTest(_system: ActorSystem) extends TestKit(_system) with ImplicitSender with FunSuiteLike with Matchers with BeforeAndAfterAll {
def this() = this(ActorSystem("TempTest"))
override def afterAll {
TestKit.shutdownActorSystem(system)
}
class WatcherActor(watchee: ActorRef) extends Actor {
var state = "initial"
context.watch(watchee)
override def receive: Receive = {
case "start" =>
state = "start"
case _: Terminated =>
state = "terminated"
}
}
test("example") {
val watchee = TestProbe()
val watcher = TestActorRef[WatcherActor](Props(new WatcherActor(watchee.ref)))
assert(watcher.underlyingActor.state === "initial")
watcher ! "start" // "start" will be sent and handled by watcher synchronously
assert(watcher.underlyingActor.state === "start")
system.stop(watchee.ref) // will cause Terminated to be sent and handled asynchronously by watcher
Thread.sleep(100) // what is the best way to avoid blocking here?
assert(watcher.underlyingActor.state === "terminated")
}
}
現在,因爲所有相關參與者使用CallingThreadDispatcher
(所有阿卡的測試傭工被使用的道具與.withDispatcher(CallingThreadDispatcher.Id)
構成),我可以有把握地認爲,當這個語句返回:
watcher ! "start"
...「開始」的消息已經被WatchingActor
處理,從而使我能夠根據在watcher.underlyingActor.state
但是,根據我的觀察,當我停止使用watchee
或system.stop
發送Kill
以它爲watchee
死亡的副作用被異步執行,另一個線程產生的Terminated
消息。
不是一個解決方案是停止watchee
,阻塞線程一段時間,然後驗證Watcher
狀態,但我想知道如何以正確的方式做到這一點(即如何確保在殺死演員是觀察者收到並處理了Terminated
消息表明它是死亡)?
試過你的代碼片段,它工作。有趣的是,它受到幾乎同樣的問題,因爲初始@ cmbaxter的回答(等候的'gracefulStop'保證目標的演員的「posStop」後返回的結果,畢竟不是'Terminated',通過目標的演員去世消耗生產) 。我試圖理解爲什麼你的剪裁工作,事實證明,它不是'gracefulStop',它使它的工作,但事實上,你發送'PoisonPill'終止演員。 – 2014-10-24 07:35:06
出於某種原因'Terminated'的,由演員死亡'PoisonPill'生產得到同步處理,而那些被死亡'Kill'或'system.stop'生產 - 異步。我還沒有想通了,爲什麼,還沒有,但最終這意味着,人們可以簡單地發送'PoisonPill'到'watchee'實現我的目標(知道什麼時候死的演員和所有'watcher's已確認),並且'gracefulStop'與解決這個問題無關(實際上,使用'gracefulStop'和'Kill'作爲消息介紹了我在上面評論中談到的競爭條件)。 – 2014-10-24 07:44:48
我也不確定。難道那是因爲Kill拋出一個異常,而PPill不會呢? – 2014-10-24 19:40:14