测试预期消息的模式匹配 [英] Pattern matching on testing expected message
问题描述
如果我不知道所有消息的详细信息,如何使用akka testkit测试预期的消息?我可以使用下划线 _吗?
How can I test expected message with akka testkit if I don't know all message details? Can I use somehow underscore "_"?
示例我可以测试:
echoActor ! "hello world"
expectMsg("hello world")
我要测试的示例
case class EchoWithRandom(msg: String, random: Int)
echoWithRandomActor ! "hi again"
expectMsg(EchoWithRandom("hi again", _))
The我不想使用的方式:
The way i don't want to use:
echoWithRandomActor ! "hi again"
val msg = receiveOne(1.second)
msg match {
case EchoWithRandom("hi again", _) => //ok
case _ => fail("something wrong")
}
推荐答案
您似乎对此无能为力,因为 expectMsg
使用 == 幕后
It doesn't look like you can do much about it, because expectMsg
uses ==
behind the scenes.
您可以尝试使用 expectMsgPF
,其中PF来自 PartialFunction
:
echoWithRandomActor ! "hi again"
expectMsgPF() {
case EchoWithRandom("hi again", _) => ()
}
更新
在最新版本(当前为 2.5.x
)中,您需要 TestProbe
。
Update
In recent versions (2.5.x
at the moment) you need a TestProbe
.
您还可以从 expectMsgPF
返回一个对象。可能是您要进行模式匹配的对象或对象的一部分。这样,您可以在 expectMsgPF
成功返回后进行进一步检查。
You can also return an object from the expectMsgPF
. It could be the object you are pattern matching against or parts of it. This way you can inspect it further after expectMsgPF
returns successfully.
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
有关更多信息,请参见 Akka测试。
See Akka Testing for more info.
这篇关于测试预期消息的模式匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!