2016-03-29 238 views
2

只需編寫單元測試,以確保演員在一定條件下關閉,所以我有一個測試,如:阿卡演員isTerminated棄用

val tddTestActor = TestActorRef[MyActor](Props(classOf[MyActor], "param1")) 
    tddTestActor ! someMessage 
    tddTestActor.isTerminated shouldBe true 

我拿起一個警告,isTerminated已被棄用。提示建議我使用context.watch()但是在單元測試中,我沒有父節點或任何上下文來觀察。

什麼將bext方式驗證tddTestActor關閉?

+0

通過cmbaxter偉大的答案,使用TestProbe ()觀看演員,然後使用expectTerminated()進行測試 – Exie

回答

2

我同意看着是完成這件事的最好方法。當我測試停止行爲時,我通常會使用TestProbe作爲觀察者來檢查我的受測者。說我有一個定義很簡單Actor如下:

class ActorToTest extends Actor{ 
    def receive = { 
    case "foo" => 
     sender() ! "bar" 
     context stop self 
    } 
} 

然後,使用specs2與阿卡結合真實TestKit我可以測試的停止行爲,像這樣:

class StopTest extends TestKit(ActorSystem()) with SpecificationLike with ImplicitSender{ 

    trait scoping extends Scope { 
    val watcher = TestProbe() 
    val actor = TestActorRef[ActorToTest] 
    watcher.watch(actor) 
    } 

    "Sending the test actor a foo message" should{ 
    "respond with 'bar' and then stop" in new scoping{ 
     actor ! "foo" 
     expectMsg("bar") 
     watcher.expectTerminated(actor) 
    } 
    } 

}