在有限状态机中更新数据

Updating data in a Finite state machine

我将 FSM 框架与 AKKA 一起使用 Java API 来管理状态转换。这是状态机的相关部分

     when(QUEUED,
            matchEvent(Exception.class, Service.class,
                (exception, dservice) -> goTo(ERROR)
                    .replying(ERROR)));


        // TODO:It seems missing from the DOC that to transition from a state , every state must be
        // listed

        // a service is in a errored state
        when(ERROR,
            matchAnyEvent((state, data) -> stay().replying("Staying in Errored state")));

        onTransition(matchState(QUEUED, ERROR, () -> {
   // Update the Service object and save it to the database


        }));

这按预期工作并且 actor 发生了正确的状态更改。在 onTansition() 块中,我想更新服务对象,在这种情况下它是有限状态机数据,如下所示

Service.setProperty(someProperty)
dbActor.tell(saveService);

这可能吗?我是否以正确的方式使用这个框架?

我想我可以做类似下面的事情

 onTransition(matchState(QUEUED,ERROR, () -> {
      nextStateData().setServiceStatus(ERROR);
      // Get the actual exception message here to save to the database
      databaseWriter.tell(nextStateData(), getSelf());

    }));

我现在如何实际测试由于此转换而更改的数据?

测试看起来像这样

   @Test
      public void testErrorState() {
        new TestKit(system) {
          {
            TestProbe probe = new TestProbe(system);
            final ActorRef underTest = system.actorOf(ServiceFSMActor.props(dbWriter));
            underTest.tell(new Exception(), getRef());
            expectMsgEquals(ERROR); // This works
           // How do I make sure the data is updated here as part of the OnTransition declaration??

          }
        };
      }

您在测试中定义了一个探测器,但您没有使用它。由于 FSM actor 将更新后的状态发送给数据库 writer actor,您可以通过用探针替换数据库 writer actor 来测试更新后的状态:

new TestKit(system) {{
  final TestProbe probe = new TestProbe(system);

  final ActorRef underTest = system.actorOf(ServiceFSMActor.props(probe.ref()));
  underTest.tell(new Exception(), getRef());
  expectMsgEquals(ERROR);

  final Service state = probe.expectMsgClass(Service.class);
  assertEquals(ERROR, state.getServiceStatus());
}};