我们有一个演员,我们正在编写单元测试,作为测试的一部分,我们想断言某些消息按特定顺序发送给另一个演员。在我们的单元测试中,接收消息的actor由Akka TestProbe
表示,它在创建时被注入到被测试的actor中。
断言消息被发送到测试探针是没有问题的,但是我们一直在努力找出断言它们以正确顺序发送的方法(我们找不到任何合适的方法来执行此操作documentation)。我们如何实现这一目标的任何想法?
下面是一个突出问题的最小实现。
实施
case class Message(message: String)
case class ForwardedMessage(message: String)
class ForwardingActor(forwardTo: ActorRef) extends Actor {
def receive = {
case Message(message) =>
forwardTo ! ForwardedMessage(message)
}
}
单元测试
class ForwardMessagesInOrderTest extends TestKit(ActorSystem("testSystem"))
with WordSpecLike
with MustMatchers {
"A forwarding actor" must {
val forwardingReceiver = TestProbe()
val forwardingActor = system.actorOf(Props(new ForwardingActor(forwardingReceiver.ref)))
"forward messages in the order they are received" in {
forwardingActor ! Message("First message")
forwardingActor ! Message("Second message")
// This is the closest way we have found of achieving what we are looking for, it asserts
// that both messages were received, but doesn't assert correct order. The test will pass
// regardless which way round we put the messages below.
forwardingReceiver.expectMsgAllOf(
ForwardedMessage("Second message"),
ForwardedMessage("First message"))
}
}
}
答案 0 :(得分:8)
我将建议对您的测试规范进行两项更改。首先,在创建受测试的actor时,使用TestActorRef
,如下所示:
val forwardingActor = TestActorRef(new ForwardingActor(forwardingReceiver.ref))
使用TestActorRef
将确保使用CallingThreadDispatcher
,从而消除测试异步代码(演员是)的任何复杂情况。完成后,您可以将断言更改为:
forwardingReceiver.expectMsg(ForwardedMessage("First message"))
forwardingReceiver.expectMsg(ForwardedMessage("Second message"))
这些断言本身就是有序的,所以如果事情不按顺序排列,它们就会失败。这应该可以解决您的问题。