Scala 测试预期消息的模式匹配
如果我不知道所有消息的详细信息,如何使用akka testkit测试预期消息?我可以用下划线“\ux”吗 我可以测试的示例:Scala 测试预期消息的模式匹配,scala,akka,Scala,Akka,如果我不知道所有消息的详细信息,如何使用akka testkit测试预期消息?我可以用下划线“\ux”吗 我可以测试的示例: echoActor ! "hello world" expectMsg("hello world") 我想测试的例子 case class EchoWithRandom(msg: String, random: Int) echoWithRandomActor ! "hi again" expectMsg(EchoWithRandom("hi again", _))
echoActor ! "hello world"
expectMsg("hello world")
我想测试的例子
case class EchoWithRandom(msg: String, random: Int)
echoWithRandomActor ! "hi again"
expectMsg(EchoWithRandom("hi again", _))
我不想使用的方式:
echoWithRandomActor ! "hi again"
val msg = receiveOne(1.second)
msg match {
case EchoWithRandom("hi again", _) => //ok
case _ => fail("something wrong")
}
看起来你对此无能为力,因为
expectMsg
使用==
您可以尝试使用,其中PF来自PartialFunction
:
echoWithRandomActor ! "hi again"
expectMsgPF() {
case EchoWithRandom("hi again", _) => ()
}
更新
在最新版本中(2.5.x
目前),您需要
您还可以从expectMsgPF
返回对象。它可能是您正在进行模式匹配的对象或其一部分。这样,您可以在expectMsgPF
成功返回后进一步检查它
import akka.testkit.TestProbe
val probe = TestProbe()
echoWithRandomActor ! "hi again"
val expectedMessage = testProbe.expectMsgPF() {
// pattern matching only
case ok@EchoWithRandom("hi again", _) => ok
// assertion and pattern matching at the same time
case ok@EchoWithRandom("also acceptable", r) if r > 0 => ok
}
// more assertions and inspections on expectedMessage
有关更多信息,请参阅。确定语法从何而来?@user6296589它被称为模式绑定器。有很多关于它的问题,比如这个:。语言规范在这里处理它: