在 akka hooks 中测试 actor 的创建(preStart)
Test actors creation in akka hooks (preStart)
我想测试 preStart() 创建正确的 actors 树(纠正我,如果我选择了错误的位置来创建 actors 树)。
class Central extends Actor {
var summer : ActorRef = _
override def preStart() = {
val printerProps = Props[Printer]
val printer = context.actorOf(printerProps, "printer")
val summerProps = Props(new Summer(printer))
summer = context.actorOf(summerProps, "summer")
}
override def receive = {
case msg =>
}
}
完整图片:
class Printer extends Actor {
override def receive = {
case msg => println(msg)
}
}
class Summer(printer: ActorRef) extends Actor {
override def receive = {
case (x: Int, y: Int) =>
printer ! x + y
}
}
任何想法,如何明确测试它?
这个答案 接近我要找的东西。但我认为因为测试原因而更改代码是个坏主意。
也许有人知道更好的解决方案。
如果您只想测试创建,您还可以从测试中从 ActorSystem 获取一个 ActorSelection,其中包含您的 Central actor (central/*) 的所有 children。
之后,向整个选择发送Identify消息(特殊akka消息)并等待响应,检查它们是否匹配。无需在您的演员中注入代码。
基于 Diego Martinoia 的回答的片段:
"The Central actor" should {
"Create Summer" in {
import scala.concurrent.duration._
implicit val timeout = Timeout(3 seconds)
val central = system.actorOf(Props[Central], "central")
val summerSelection = system.actorSelection("user/central/summer")
val summerRef = Await.result(summerSelection.resolveOne(), 3 seconds)
}
}
我想测试 preStart() 创建正确的 actors 树(纠正我,如果我选择了错误的位置来创建 actors 树)。
class Central extends Actor {
var summer : ActorRef = _
override def preStart() = {
val printerProps = Props[Printer]
val printer = context.actorOf(printerProps, "printer")
val summerProps = Props(new Summer(printer))
summer = context.actorOf(summerProps, "summer")
}
override def receive = {
case msg =>
}
}
完整图片:
class Printer extends Actor {
override def receive = {
case msg => println(msg)
}
}
class Summer(printer: ActorRef) extends Actor {
override def receive = {
case (x: Int, y: Int) =>
printer ! x + y
}
}
任何想法,如何明确测试它?
这个答案 接近我要找的东西。但我认为因为测试原因而更改代码是个坏主意。
也许有人知道更好的解决方案。
如果您只想测试创建,您还可以从测试中从 ActorSystem 获取一个 ActorSelection,其中包含您的 Central actor (central/*) 的所有 children。
之后,向整个选择发送Identify消息(特殊akka消息)并等待响应,检查它们是否匹配。无需在您的演员中注入代码。
基于 Diego Martinoia 的回答的片段:
"The Central actor" should {
"Create Summer" in {
import scala.concurrent.duration._
implicit val timeout = Timeout(3 seconds)
val central = system.actorOf(Props[Central], "central")
val summerSelection = system.actorSelection("user/central/summer")
val summerRef = Await.result(summerSelection.resolveOne(), 3 seconds)
}
}