如果我不知道所有消息详细信息,如何使用akka testkit测试预期消息?我能以某种方式使用下划线"_"吗?
示例我可以测试:
echoActor ! "hello world"
expectMsg("hello world")
Run Code Online (Sandbox Code Playgroud)
我要测试的例子
case class EchoWithRandom(msg: String, random: Int)
echoWithRandomActor ! "hi again"
expectMsg(EchoWithRandom("hi again", _))
Run Code Online (Sandbox Code Playgroud)
我不想使用的方式:
echoWithRandomActor ! "hi again"
val msg = receiveOne(1.second)
msg match {
case EchoWithRandom("hi again", _) => //ok
case _ => fail("something wrong")
}
Run Code Online (Sandbox Code Playgroud)
Ion*_*tan 28
它看起来并不像你可以做的不多,因为expectMsg
使用了==
幕后.
您可以尝试使用expectMsgPF
,PF来自PartialFunction
:
echoWithRandomActor ! "hi again"
expectMsgPF() {
case EchoWithRandom("hi again", _) => ()
}
Run Code Online (Sandbox Code Playgroud)
在最近的版本(2.5.x
目前),你需要一个TestProbe
.
你也可以从中返回一个对象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
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅Akka Testing.