2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.cluster.raft;
12 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
14 * This program and the accompanying materials are made available under the
15 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
16 * and is available at http://www.eclipse.org/legal/epl-v10.html
19 import akka.actor.Actor;
20 import akka.actor.ActorRef;
21 import akka.actor.ActorSystem;
22 import akka.actor.PoisonPill;
23 import akka.actor.Props;
24 import akka.testkit.JavaTestKit;
25 import akka.testkit.TestActorRef;
26 import java.util.LinkedList;
27 import java.util.List;
28 import org.slf4j.Logger;
29 import org.slf4j.LoggerFactory;
32 * TestActorFactory provides methods to create both normal and test actors and to kill them when the factory is closed
33 * The ideal usage for TestActorFactory is with try with resources, <br/>
36 * try (TestActorFactory factory = new TestActorFactory(getSystem())){
37 * factory.createActor(props);
38 * factory.createTestActor(props);
39 * factory.generateActorId("leader-");
43 public class TestActorFactory implements AutoCloseable {
44 private final ActorSystem system;
45 List<ActorRef> createdActors = new LinkedList<>();
46 Logger LOG = LoggerFactory.getLogger(getClass());
47 private static int actorCount = 1;
49 public TestActorFactory(ActorSystem system){
54 * Create a normal actor with an auto-generated name
59 public ActorRef createActor(Props props){
60 ActorRef actorRef = system.actorOf(props);
61 createdActors.add(actorRef);
66 * Create a normal actor with the passed in name
68 * @param actorId name of actor
71 public ActorRef createActor(Props props, String actorId){
72 ActorRef actorRef = system.actorOf(props, actorId);
73 createdActors.add(actorRef);
78 * Create a test actor with the passed in name
84 public <T extends Actor> TestActorRef<T> createTestActor(Props props, String actorId){
85 TestActorRef<T> actorRef = TestActorRef.create(system, props, actorId);
86 createdActors.add(actorRef);
91 * Create a test actor with an auto-generated name
96 public <T extends Actor> TestActorRef<T> createTestActor(Props props){
97 TestActorRef<T> actorRef = TestActorRef.create(system, props);
98 createdActors.add(actorRef);
103 * Generate a friendly but unique actor id/name
107 public String generateActorId(String prefix){
108 return prefix + actorCount++;
112 public void close() {
113 new JavaTestKit(system) {{
114 for(ActorRef actor : createdActors) {
116 LOG.info("Killing actor {}", actor);
117 actor.tell(PoisonPill.getInstance(), ActorRef.noSender());
118 expectTerminated(duration("5 seconds"), actor);