首页 > 解决方案 > 键入 Akka 测试套件中的 expectMsgAnyOf 和 expectMsgAllOf

问题描述

我有 akka testkit(经典)和方法expectMsgAnyOf,并且expectMsgAllOfTestKit课堂上,让我检查几条消息:

    "reply to a greeting" in {
     labTestActor ! "greeting"
     expectMsgAnyOf("hi", "hello")
   }

   "reply with favorite tech" in {
     labTestActor ! "favoriteTech"
     expectMsgAllOf("Scala", "Akka")
   }

TestKit我想用键入的 Akka testkit 重写这些测试,但在和TestProbe类中找不到这些方法。你能帮我检查消息的顺序和任何消息吗?

标签: akkaakka-testkitakka-typed

解决方案


You could implement equivalents in typed as

def expectMsgAnyOf[T](probe: TestProbe[T])(candidates: T*): Unit = {
  val c = candidates.toSet
  val nextMsg = probe.receiveMessage()
  if (!c(nextMsg)) {
    throw new AssertionError(s"Expected one of $c, got $nextMsg")
  }
}

def expectMsgAllOf[T](probe: TestProbe[T])(expected: T*): Unit = {
  import scala.collection.mutable.Buffer

  val e = Buffer(expected: _*)
  val nextMsgs = probe.receiveMessages(candidates.size)
  nextMsgs.foreach { msg =>
    val idx = e.indexOf(msg)
    if (idx == -1) {
      throw new AssertionError(s"Received unexpected message: $msg")
    }
    e.remove(idx)
  }

  if (e.nonEmpty) {
    throw new AssertionError(s"Expected messages not received: ${e.mkString(",")}")
  }
}

推荐阅读