2016-03-04 78 views
0

我想測試一個演員,這取決於另一個演員。在以下測試中,ActorAMessageA發送到ActorB,並且期望返回MessageB用TestKit測試嘲笑的演員的期望消息

由於這是一個單元測試ActorB,我嘲笑ActorA。我現在的問題是,我想確保ActorA獲得MessageA,但是當我打電話給expectMsg(請參閱註釋行),整個自動駕駛儀似乎不再工作。

我在這裏做錯了什麼?

class MyTest(_system: ActorSystem) extends TestKit(_system) 
    with WordSpecLike 
    with BeforeAndAfterAll { 

    object Start 
    object MessageA 
    object MessageB 

    def this() = this(ActorSystem("TestSpec")) 

    override def afterAll() { 
    system.shutdown() 
    } 

    // will later be mocked 
    class ActorA extends Actor { 
    def receive = { 
     case MessageA => sender() ! MessageB 
    } 
    } 

    class ActorB(actorA: ActorRef) extends Actor { 
    def receive = { 
     case Start => actorA ! MessageA 
     case MessageB => println("Got MessageB") 
    } 
    } 

    "" should { 
    "work" in { 
     val actorA = TestProbe() 

     actorA.setAutoPilot(new AutoPilot { 
     override def run(sender: ActorRef, msg: Any): AutoPilot = { 
      msg match { 
      case MessageA => sender ! MessageB 
      } 
      TestActor.KeepRunning 
     } 
     }) 

     // this will break the test 
     //actorA.expectMsg(MessageA) 

     val actor = system.actorOf(Props(new ActorB(actorA.ref))) 
     actor ! Start 
    } 
    } 

} 

回答

0

發送開始到你的ActorB後,你應該期待MessageA。

val actor = system.actorOf(Props(new ActorB(actorA.ref))) 
    actor ! Start 

    // this will not break the test 
    actorA.expectMsg(MessageA)