我正在尝试使用AkkaTestKit测试我的actor逻辑。问题是我的演员使用ask
模式。所以我需要以某种方式回答。它看起来像这样:
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?
答案 0 :(得分:1)
为了使代码更容易测试,请为actor指定执行者actor(处理AskExecution
消息的actor)。
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]])
}