在 PersistentActor 中使用 context.become 时,我遇到了一种奇怪的行为(不确定持久性是否与问题的原因有关)。我的代码是这样的:
class MyActor extends PersistentActor {
import context._
// Messages
case object Start
case object Ready
case object MessageX
// Events
case object Started
def recieveRecover: Receive = { /* Not relevant, I think */}
def receiveCommand: Receive = idle
def idle: Receive = {
case Start =>
persist(Started) { _ =>
sender() ! Ready
become(ready)
}
}
def ready: Receive = {
case MessageX => doSomething()
}
}
我在同一个 MyActorSpec 文件中有两个测试。第一个只是测试“空闲”状态,第二个测试“就绪”状态:
"Test A" in {
val actorRef = system.actorOf( MyActor.props(), "test-A-actor" )
actorRef ! Start
expectMsg(Ready)
}
"Test B" in {
val actorRef = system.actorOf( MyActor.props(), "test-B-actor" )
actorRef ! Start
expectMsg(Ready) /* It fails here because for some reason the actorRef
was created with its 'receiveCommand' block equal to
the 'ready' block and not equal to the 'idle' block as its suppossed to.
So it timeouts here waiting for the message which is not handled in
the 'ready' block */
actorRef ! MessageX
testSomethingAboutTheMessageX()
}
如果我运行这两个测试,第一个成功,但第二个失败等待就绪消息(如第二个测试中的注释中所述)。如果我只运行第二个测试,它就会通过。所以,我不确定我在定义演员时是否做错了什么。
更新:我尝试按照建议删除Started
事件(persist(Started)
部分)的持久性,并且测试按预期工作(两个参与者都是在该idle
州创建的)。所以,发生的事情是第一个actor实例上的事件被持久化,然后第二个actor实例正在重放它们,这是因为actor实例是用相同的persistenceId
(DOH!)创建的。因此,使测试独立的方法是简单地用不同的persistenceId
.