テストするあなたのコードを簡単にするために、あなたの俳優エグゼキュータの俳優への参照を与える(ハンドル俳優:次のように私はそれを使用するテストでは
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]])
}
それは 'TestProbe'を注入し、メッセージが送信されていることを確認するためにそれを使用して応答するためにさらに簡単です彼らへ。新しいアクタークラスを作成する必要はなく、他のアクターの動作が状態に依存する場合は特に便利です。 –