【问题标题】:Akka: Test scheduled actors using TestkitAkka:使用 Testkit 测试调度的 Actor
【发布时间】:2020-09-02 13:47:51
【问题描述】:

我有一个父演员,它创建一个子演员,子演员每分钟都会向父母打招呼,如下所示

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

我是 Actor 系统的新手,如何使用 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")
     }
    }

【问题讨论】:

    标签: scala akka testkit actorsystem


    【解决方案1】:

    您可以在 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")
      }
     }
    }
    

    我会做的,不要等待那么久,将延迟超时放在配置中,并在测试场景中将其更改为几毫秒。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-19
      • 2017-10-13
      • 1970-01-01
      • 2019-02-12
      • 2012-05-20
      • 1970-01-01
      • 2015-10-25
      • 2018-05-08
      相关资源
      最近更新 更多