如何使用Akka TestKit响应失败的Ask模式?

Wil*_*ter 5 scala akka akka-testkit

我有一个Akka演员,该演员使用Ask模式从子演员中检索Future,并根据成功和失败采取行动。我无法弄清楚如何模仿儿童演员并以失败作为回应。

这是代码:

import java.util.concurrent.TimeUnit
import akka.actor.{Actor, ActorRef, ActorSystem, Props}
import akka.pattern.ask
import akka.testkit.{ImplicitSender, TestKitBase, TestProbe}
import akka.util.Timeout
import org.specs2.mutable.Specification
import org.specs2.specification.Scope
import scala.util.{Failure, Success}

class Parent(child: ActorRef) extends Actor {
  implicit val timeout = Timeout(5, TimeUnit.SECONDS)
  import context.dispatcher

  override def receive: Receive = {
    case "go" => {
      val senderRef = sender()
      (child ? "question").mapTo[String] onComplete {
        case Success("answer") =>
          senderRef ! "child responded with a successful answer"
        case Failure(throwable) =>
          senderRef ! "child responded with a failure"
      }
    }
  }
}

class SimplifiedProblemSpec extends Specification {

  "The Parent Actor" should {
    "act on success" in new TestScope {
      parent ! "go"
      childProbe.expectMsg("question")
      childProbe.reply("answer")
      expectMsg("child responded with a successful answer")
    }
    "act on failure" in new TestScope {
      parent ! "go"
      childProbe.expectMsg("question")
      // How to reply with failure?
      expectMsg("child responded with a failure")
    }
  }

}

abstract class TestScope extends Scope with TestKitBase with ImplicitSender {
  implicit lazy val system: ActorSystem = ActorSystem()

  val childProbe = TestProbe()
  val parent = system.actorOf(Props(classOf[Parent], childProbe.ref), "Parent")

}
Run Code Online (Sandbox Code Playgroud)

任何帮助将非常感激。

谢谢

ka4*_*eli 4

您可以使用包Status.Failure中的案例类akka.actor。来自文档:

该类/消息类型优选地用于指示所执行的某些操作的失败。例如,它用于通过 AskSupport 来表示失败 (ask/?)。