代码之家  ›  专栏  ›  技术社区  ›  user_mda

在有限状态机中更新数据

  •  2
  • user_mda  · 技术社区  · 8 年前

    我将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
    
    
            }));
    

    这会按预期工作,并且参与者会发生正确的状态更改。在 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??
    
              }
            };
          }
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   Jeffrey Chung    8 年前

    您已在测试中定义了探测器,但未使用它。由于FSM actor将更新的状态发送给数据库编写器actor,因此可以通过将数据库编写器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());
    }};