2016-03-29 146 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) 
    } 
    } 

}