2017-08-03 70 views
0

我想用AkkaTestKit測試我的演員邏輯。問題是我的演員使用ask模式。所以我需要以某種方式回答。它看起來像這樣:回答AkkaTestKit

case class AskExecution(id: Long) 

    override def receive: Receive = { 
    case id : Long => 
     implicit val dispatcher = context.dispatcher 
     implicit val timeout = Timeout(10 seconds) 
     val executor = sender 

     //How to answer this? 
     val f = executor ? AskExecution(id) map(v => v.asInstanceOf[Option[Long]]) 
     f.onComplete{ 
     case Success(k) => 
     case Failure(_) => 
     } 
    } 

在測試中,我使用它,如下所示:

val ca = TestActorRef(new TheActor()) 
ca ! 0L //I send 0, Now I want to answer the ask 
     //How to do so? 

回答

1

爲了使你的代碼更易於測試,給你的演員執行人演員的參考(處理該演員消息)。

import akka.pattern.pipe 

class TheActor(executor: ActorRef) extends Actor { 
    def receive = { 
    case id: Long => 
     val s = sender 
     implicit val dispatcher = context.dispatcher 
     implicit val timeout = 10.seconds 
     (executor ? AskExecution(id)).mapTo[Option[Long]].pipeTo(s) 
} 

class Executor extends Actor { 
    def receive = { 
    case AskExecution(id) => 
     // do something to get a result 
     val result: Option[Long] = ??? 
     sender ! result 
    } 
} 

test,假設你的測試類擴展TestKit並在ImplicitSender特質混合物:

val executor = system.actorOf(Props[Executor]) 
val theActor = system.actorOf(Props(classOf[TheActor], executor)) 

within(10.seconds) { 
    theActor ! 0L 
    expectMsgClass(classOf[Option[Long]]) 
} 

// test the executor directly 
within(10.seconds) { 
    executor ! AskExecution(3L) 
    expectMsgClass(classOf[Option[Long]]) 
} 
+0

它注入了'TestProbe',並用它來驗證消息已發送和迴應更簡單給他們。不需要創建一個新的演員類,如果其他演員的行爲取決於狀態,則特別有用。 –