2017-08-03 2 views
0

私はアクカロジックをAkkaTestKitでテストしようとしています。問題は私の俳優がaskパターンを使用していることです。だから私は何とか答えなければならない。 、Answer AkkaTestKitで質問する

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

答えて

1

テストするあなたのコードを簡単にするために、あなたの俳優エグゼキュータの俳優への参照を与える(ハンドル俳優:次のように私はそれを使用するテストでは

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(_) => 
     } 
    } 

:それはこのように見えますAskExecutionメッセージ)。 test

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 
    } 
} 

、あなたのテストクラスが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'を注入し、メッセージが送信されていることを確認するためにそれを使用して応答するためにさらに簡単です彼らへ。新しいアクタークラスを作成する必要はなく、他のアクターの動作が状態に依存する場合は特に便利です。 –