gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 01:17:31 24 4
gpt4 key购买 nike

我有一个 Akka Actor,它使用 Ask 模式从子 Actor 检索 Future 并对成功和失败采取行动。我不知道如何模拟 child Actor 并以失败作为回应。

这是代码:

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")

}

任何帮助将非常感激。

谢谢

最佳答案

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

This class/message type is preferably used to indicate failure of some operation performed. As an example, it is used to signal failure with AskSupport is used (ask/?).

关于scala - 如何使用 Akka TestKit 响应失败的 Ask 模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32669575/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com