我试图让测试探针在收到任何消息时回复确认。
我在测试中编写了以下代码,但它不起作用:
val chgtWriter = new TestProbe(system) {
def receive: Receive = {
case m => println("receive messagereplying with ACK"); sender() ! ACK
}
}
有没有办法做到这一点。实际将消息发送到测试探针的参与者肯定是在除 TestThread 之外的另一个线程上运行。您可以在下面看到当前制作的完整测试。
feature("The changeSetActor periodically fetch new change set following a schedule") {
scenario("A ChangeSetActor fetch new changeset from a Fetcher Actor that return a full and an empty ChangeSet"){
Given("a ChangeSetActor with a schedule of fetching a message every 10 seconds, a ChangeFetcher and a ChangeWriter")
val chgtFetcher = TestProbe()
val chgtWriter = new TestProbe(system) {
def receive: Receive = {
case m => println("receive message {} replying with ACK"); sender() ! ACK
}
}
val fromTime = Instant.now().truncatedTo(ChronoUnit.SECONDS)
val chgtActor = system.actorOf(ChangeSetActor.props(chgtWriter.ref, chgtFetcher.ref, fromTime))
When("all are started")
Then("The Change Fetcher should receive at least 3 messages from the ChangeSetActor within 40 seconds")
var changesetSNum = 1
val received = chgtFetcher.receiveWhile( 40 seconds) {
case FetchNewChangeSet(m) => {
println(s"received: FetchNewChangeSet(${m}")
if (changesetSNum == 1) {
chgtFetcher.reply(NewChangeSet(changeSet1))
changesetSNum += 1
}
else
chgtFetcher.reply(NoAvailableChangeSet)
}
}
received.size should be (3)
}
}
changeSetActor 已经过全面测试并且可以正常工作。测试与 ChangeWriter 挂起。它永远不会在接收方法中收到消息。
EDIT1(跟随@Jakko anser)
自动驾驶仪如下:
val probe = TestProbe() probe.setAutoPilot(new TestActor.AutoPilot { def run(sender: ActorRef, msg: Any): TestActor.AutoPilot = msg match { case "stop" ⇒ TestActor.NoAutoPilot case x ⇒ **testActor.tell(x, sender)**; TestActor.KeepRunning } })
尽管到目前为止给出的所有解释都很清楚,但官方示例中令人困惑的是参考“testActor”。这里的 testActor 是谁?那时没有该名称的变量声明。