Akka TestKit如何等待处理消息
在我的TestKit测试中
"A History Actor" must {
// given
val historyActorRef = TestActorRef(new HistoryActor("history-file.log")) // Creation of the TestActorRef
val writerActorRef = TestActorRef(new WriterActor("history-file.log")) // Creation of the TestActorRef
historyActorRef.underlyingActor.writerActor = writerActorRef
"receive messages and change state" in { // integration-like test
// This call is synchronous. The actor receive() method will be called in the current thread
// when
historyActorRef ! WriteMsg("line 1")
// then (1) - got WriteResult (from WriterActor as result of getting WriteMsg)
within(200 millis) {
expectMsg(WriteResult(1, 7))
}
// then (2) - state
historyActorRef.underlyingActor.lastWrite must equal(WriteResult(1,7)) // With actorRef.underlyingActor, we can access the react actor instance created by Akka
}
}
此测试失败,因为它仍然是 WriteResult(0,0)
在_2777276中工作的方式:
case cmd: WriteMsg => {
log.info("forwarding " + cmd + " to the writer" )
writerActor ! cmd
}
case result: WriteResult => {
log.info("WriteResult: " + result)
lastWrite = result // update the state
}
那么,当我们检查结果时,如何进行测试以确保 WriteResult
已经处理好了?
附:我想我应该考虑单独测试 WriterActor
,但是假设我想要那种类似集成的测试 .
2 years ago
如果你还没有这样做,你需要在
TestActorRef
中包装这两个被测试的actor . 这将确保两者都使用调用线程调度程序从测试场景中获取异步性 . 您也可以考虑将writeActor
替换为TestProbe
进行测试,然后模拟它的行为 .Update
根据我的意见:
当你说
expectMsg
时,你说的是测试本身(由TestKit
引入的隐式发送者)正在从它最初发送的消息中接收响应消息以启动测试 . 我不知道测试工具断言是如何工作的 . 只需验证内部状态是否已更新就足够了