Akka:使用Testkit测试预定的演员

问题描述

我有一个父演员,它创建了一个子演员,并且该子演员每分钟都会如下向父母致意

    class Masteractor extends Actor with ActorLogging {

     override def receive: Receive = {
       case "Greet" =>
         print("hey child!!")
       case "CreateChild" =>
        context.actorOf(Props[ChildActor])
      }
    }

    class ChildActor extends Actor with ActorLogging {

    import context.dispatcher

    override def preStart(): Unit = {
      super.preStart()
      context.system.scheduler.schedule(Duration("1 minutes").asInstanceOf[FiniteDuration],Duration("1 minutes").asInstanceOf[FiniteDuration],context.parent,"Greet")
    }

    override def receive: Receive = {
      case _ =>
        print("child receives something")
      }
    }

我是演员系统的新手,如何使用TestKit测试计划方案?

我在测试中尝试了类似以下内容的操作,但这不起作用

    "Master actor" should {
     "receive a Greet message every minute" in {
      val probe = TestProbe

      val actor = system.actorOf(Props(new Child() {

        import context.dispatcher

        override def preStart() =
          context.system.scheduler.scheduleOnce(Duration("1 seconds").asInstanceOf[FiniteDuration],probe.ref,"Greet")
      }))

      probe.expectMsg("Greet")
     }
    }

解决方法

您可以在Akka文档测试的timing-assertions部分中阅读有关此内容的信息。有within函数可以为您提供帮助。

例如,您可以尝试:

"Master actor" should {
 "receive a Greet message every minute" in {
   within(62 seconds) {
    val probe = TestProbe

    val actor = system.actorOf(Props[Child])
    probe.expectMsg("Greet")
  }
 }
}

我要做的是不要将等待时间太长,而是将延迟超时放入配置中,并在测试场景中将其更改为几毫秒。