在akka-testkit的帮助下测试延迟消息

有两个演员 - ProducerActorConsumerActor . 生产环境 者有一个调度程序,每个 2000 ms 发送 "Tick" 消息给自己 . 之后, 生产环境 者向消费者发送 "Hello" 消息:

class ProducerActor(consumer: ActorRef) extends Actor {
    override def receive: Receive = {
      case "Tick" =>
          ...
          // some code which takes < 1 ms
          ...
          consumer ! "Hello"
    }

    override def preStart: Unit = 
      context.system
         .scheduler
         .schedule(2000 milliseconds, 2000 milliseconds, self, "Tick")
}

当消费者角色收到"Hello"消息时,是否可以测试案例? 2000 ms ?因此,如果在句号 < 2000 ms> 2000 ms 中收到消息,则测试将断言错误 .

例如:

"Consumer test" should {
    "receive message each 2000 ms" in {
       ...
       val consumer = TestProbe()
       val producer = system.actorOf(Props(new ProducerActor(consumer.ref))
       ...
       consumer.howToExpectDelayedMessage(minDelay = 2000 millis, "Hello")

    }
}

--- UPD ---

我已经找到了以下适合我的解决方案:

"Consumer test" should {
    "receive message each 2000 ms" in {

       val consumer = TestProbe()
       val producer = system.actorOf(Props(new ProducerActor(consumer.ref))

       // check the first ten periods
       (0 to 10) foreach { _ =>
         consumer.expectNoMsg(2000 millis)
         consumer.expectMsg("Hello")
       }

    }
}

但如果有一个更好的解决方案来完成这项任务,那么如果你能分享就会很棒 .

回答(0)