如何为抽象的Akka演员的监督策略编写测试用例

时间:2016-07-19 14:14:24

标签: akka

有人可以帮助为以下抽象的Akka actor伪代码编写测试用例。

我面临的问题是所有监督策略消息(作为测试用例的一部分发送)正由父行为者使用,而不是将其监督策略应用于其子女。

父抽象actor创建子项。

Abstract class Parent extends UntypedActor {

  String name;
  int noOfChildActors;
  //this set is used to manage the children i.e noOfChildActors = children.size()
  Set<ActorRef> children;     

  public Parent(String name, int noOfChildActors, Props childProps){
    this.name=name;
    this.noOfChildActors = noOfChildActors;
    createChildern(childProps);
  }

  public void createChildern(Props props){
     for(int i = 0 ; i< no_of_child_actors;i++)
     final ActorRef actor = getContext().actorOf(props, "worker"+i);
     getContext().watch(actor);
     children.add(actor);
    }

  @Override
    public void onReceive(final Object message) {
     //actor functionalities goes here.
    }

   @Override
    public SupervisorStrategy supervisorStrategy() {
        return defaultSupervisorStrategy();
    }

    private SupervisorStrategy defaultSupervisorStrategy() {
        return new AllForOneStrategy(-1, Duration.Inf(), new Strategy());
    }

  private class Strategy implements Function<Throwable, Directive> {
   @Override
        public Directive apply(final Throwable t) {
    //my own strategies.
    }
  }
//child managing methods.
//Abstract functions  
} 

扩展Parent类的子类

class Child extends Parent{

  String name;

  public static Props props(final String name, int noOfChildActors, Props childProps) {
        return Props.create(Child.class, name, noOfChildActors, childProps);
    }

  public Child(String name, int noOfChildActors, Props childProps){
    super(name, noOfChildActors, childProps);
  }

//followed by my abstract function definition
}

//测试用例

    private static final FiniteDuration WAIT_TIME = Duration.create(5, TimeUnit.SECONDS);
    JavaTestKit sender = new JavaTestKit(system);
    final Props props =  Child.Props("name", 3, Props.empty());
    ActorRef consumer = system.actorOf(props, "test-supervision");
    final TestProbe probe = new TestProbe(system);
    probe.watch(consumer);
    consumer.tell(ActorInitializationException.class, sender.getRef());
    probe.expectMsgClass(WAIT_TIME, Terminated.class);

1 个答案:

答案 0 :(得分:1)

Akka中的parent概念不是类层次结构中的父级,而是actor树中的父级,因此在示例代码中,类Child实际上不是类的子级{ {1}}。在正常情况下,子actor不会扩展父类的类。

通过使用Parent启动子项,actor可以是父项,在此之后,子项中的任何未处理的异常都将以父项的监督逻辑结束。

在此处阅读更多文档 http://doc.akka.io/docs/akka/2.4/general/actor-systems.html#Hierarchical_Structurehttp://doc.akka.io/docs/akka/2.4/java/fault-tolerance.html