diff --git a/akka-actor-tests/src/test/java/akka/actor/JavaAPI.java b/akka-actor-tests/src/test/java/akka/actor/JavaAPI.java index 1f8e198e98..9abce884bf 100644 --- a/akka-actor-tests/src/test/java/akka/actor/JavaAPI.java +++ b/akka-actor-tests/src/test/java/akka/actor/JavaAPI.java @@ -4,35 +4,27 @@ package akka.actor; -import akka.actor.ActorSystem; import akka.event.Logging; import akka.event.Logging.LoggerInitialized; import akka.japi.Creator; import akka.routing.CurrentRoutees; import akka.routing.FromConfig; import akka.routing.NoRouter; +import akka.testkit.AkkaJUnitActorSystemResource; import akka.testkit.AkkaSpec; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.ClassRule; import org.junit.Test; import static org.junit.Assert.*; public class JavaAPI { - private static ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("JAvaAPI", AkkaSpec.testConf()); - @BeforeClass - public static void beforeAll() { - system = ActorSystem.create("JavaAPI", AkkaSpec.testConf()); - } + private final ActorSystem system = actorSystemResource.getSystem(); - @AfterClass - public static void afterAll() { - system.shutdown(); - system = null; - } - // compilation tests @SuppressWarnings("unused") public void mustCompile() { diff --git a/akka-actor-tests/src/test/java/akka/actor/JavaExtension.java b/akka-actor-tests/src/test/java/akka/actor/JavaExtension.java index 5a054a81b8..c0dc77287f 100644 --- a/akka-actor-tests/src/test/java/akka/actor/JavaExtension.java +++ b/akka-actor-tests/src/test/java/akka/actor/JavaExtension.java @@ -3,14 +3,10 @@ */ package akka.actor; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.*; import akka.testkit.AkkaSpec; - import com.typesafe.config.ConfigFactory; -import com.typesafe.config.Config; import static org.junit.Assert.*; @@ -47,20 +43,13 @@ public class JavaExtension { } } - private static ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("JavaExtension", + ConfigFactory.parseString("akka.extensions = [ \"akka.actor.JavaExtension$TestExtensionId\" ]") + .withFallback(AkkaSpec.testConf())); - @BeforeClass - public static void beforeAll() { - Config c = ConfigFactory.parseString("akka.extensions = [ \"akka.actor.JavaExtension$TestExtensionId\" ]") - .withFallback(AkkaSpec.testConf()); - system = ActorSystem.create("JavaExtension", c); - } - - @AfterClass - public static void afterAll() { - system.shutdown(); - system = null; - } + private final ActorSystem system = actorSystemResource.getSystem(); @Test public void mustBeAccessible() { diff --git a/akka-actor-tests/src/test/java/akka/actor/StashJavaAPI.java b/akka-actor-tests/src/test/java/akka/actor/StashJavaAPI.java index 77ea804559..88b4b0da36 100644 --- a/akka-actor-tests/src/test/java/akka/actor/StashJavaAPI.java +++ b/akka-actor-tests/src/test/java/akka/actor/StashJavaAPI.java @@ -1,26 +1,18 @@ package akka.actor; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; import com.typesafe.config.ConfigFactory; public class StashJavaAPI { - private static ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("StashJavaAPI", ActorWithBoundedStashSpec.testConf()); - @BeforeClass - public static void beforeAll() { - system = ActorSystem.create("StashJavaAPI", - ConfigFactory.parseString(ActorWithStashSpec.testConf())); - } - - @AfterClass - public static void afterAll() { - system.shutdown(); - system = null; - } + private final ActorSystem system = actorSystemResource.getSystem(); @Test public void mustBeAbleToUseStash() { diff --git a/akka-actor-tests/src/test/java/akka/dispatch/JavaFutureTests.java b/akka-actor-tests/src/test/java/akka/dispatch/JavaFutureTests.java index ec494e542c..1530543dc8 100644 --- a/akka-actor-tests/src/test/java/akka/dispatch/JavaFutureTests.java +++ b/akka-actor-tests/src/test/java/akka/dispatch/JavaFutureTests.java @@ -1,16 +1,14 @@ package akka.dispatch; -import akka.util.Timeout; +import akka.testkit.AkkaJUnitActorSystemResource; import akka.actor.ActorSystem; import akka.japi.*; +import org.junit.ClassRule; import scala.concurrent.Await; import scala.concurrent.Future; import scala.concurrent.Promise; import scala.concurrent.duration.Duration; -import akka.testkit.TestKitExtension; -import org.junit.AfterClass; -import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; @@ -26,23 +24,13 @@ import akka.testkit.AkkaSpec; public class JavaFutureTests { - private static ActorSystem system; - private static Timeout t; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("JavaFutureTests", AkkaSpec.testConf()); + private final ActorSystem system = actorSystemResource.getSystem(); private final Duration timeout = Duration.create(5, TimeUnit.SECONDS); - @BeforeClass - public static void beforeAll() { - system = ActorSystem.create("JavaFutureTests", AkkaSpec.testConf()); - t = TestKitExtension.get(system).DefaultTimeout(); - } - - @AfterClass - public static void afterAll() { - system.shutdown(); - system = null; - } - @Test public void mustBeAbleToMapAFuture() throws Exception { diff --git a/akka-actor-tests/src/test/scala/akka/actor/ActorSystemSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/ActorSystemSpec.scala index bb93c9bb8a..12314471ec 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/ActorSystemSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/ActorSystemSpec.scala @@ -147,7 +147,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend } "allow valid names" in { - ActorSystem("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-").shutdown() + shutdown(ActorSystem("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-")) } "support extensions" in { @@ -199,14 +199,14 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend val system = ActorSystem() system.isTerminated must be(false) system.shutdown() - system.awaitTermination() + system.awaitTermination(10 seconds) system.isTerminated must be(true) } "throw RejectedExecutionException when shutdown" in { val system2 = ActorSystem("AwaitTermination", AkkaSpec.testConf) system2.shutdown() - system2.awaitTermination(5 seconds) + system2.awaitTermination(10 seconds) intercept[RejectedExecutionException] { system2.registerOnTermination { println("IF YOU SEE THIS THEN THERE'S A BUG HERE") } @@ -275,7 +275,7 @@ class ActorSystemSpec extends AkkaSpec(ActorSystemSpec.config) with ImplicitSend val t = probe.expectMsg(Terminated(a)(existenceConfirmed = true, addressTerminated = false)) t.existenceConfirmed must be(true) t.addressTerminated must be(false) - system.shutdown() + shutdown(system) } "shut down when /user escalates" in { diff --git a/akka-actor-tests/src/test/scala/akka/actor/DeployerSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/DeployerSpec.scala index 004d5ea921..606a64df52 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/DeployerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/DeployerSpec.scala @@ -132,7 +132,7 @@ class DeployerSpec extends AkkaSpec(DeployerSpec.deployerConf) { } """, ConfigParseOptions.defaults).withFallback(AkkaSpec.testConf) - ActorSystem("invalid", invalidDeployerConf).shutdown() + shutdown(ActorSystem("invalid", invalidDeployerConf)) } } diff --git a/akka-actor-tests/src/test/scala/akka/actor/FSMActorSpec.scala b/akka-actor-tests/src/test/scala/akka/actor/FSMActorSpec.scala index 383165cf2a..b37a9b15aa 100644 --- a/akka-actor-tests/src/test/scala/akka/actor/FSMActorSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/actor/FSMActorSpec.scala @@ -295,7 +295,7 @@ class FSMActorSpec extends AkkaSpec(Map("akka.actor.debug.fsm" -> true)) with Im } } } finally { - fsmEventSystem.shutdown() + TestKit.shutdownActorSystem(fsmEventSystem) } } diff --git a/akka-actor-tests/src/test/scala/akka/event/EventStreamSpec.scala b/akka-actor-tests/src/test/scala/akka/event/EventStreamSpec.scala index bd14fb42e7..10b9d18795 100644 --- a/akka-actor-tests/src/test/scala/akka/event/EventStreamSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/event/EventStreamSpec.scala @@ -104,7 +104,7 @@ class EventStreamSpec extends AkkaSpec(EventStreamSpec.config) { expectMsgAllOf(m, Logging.Debug(sys.deadLetters.path.toString, sys.deadLetters.getClass, "unhandled message from " + sys.deadLetters + ": 42")) sys.eventStream.unsubscribe(testActor) } finally { - sys.shutdown() + shutdown(sys) } } diff --git a/akka-actor-tests/src/test/scala/akka/event/LoggerSpec.scala b/akka-actor-tests/src/test/scala/akka/event/LoggerSpec.scala index aa8217b237..465a124fd5 100644 --- a/akka-actor-tests/src/test/scala/akka/event/LoggerSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/event/LoggerSpec.scala @@ -99,8 +99,7 @@ class LoggerSpec extends WordSpec with MustMatchers { probe.expectNoMsg(0.5.seconds.dilated) } } finally { - system.shutdown() - system.awaitTermination(5.seconds.dilated) + TestKit.shutdownActorSystem(system) } } out @@ -139,8 +138,7 @@ class LoggerSpec extends WordSpec with MustMatchers { probe1.expectMsg("log it") probe2.expectMsg("log it") } finally { - system.shutdown() - system.awaitTermination(5.seconds.dilated) + TestKit.shutdownActorSystem(system) } } } @@ -165,8 +163,7 @@ class LoggerSpec extends WordSpec with MustMatchers { try { SerializationExtension(s).serialize(Warning("foo", classOf[String])) } finally { - s.shutdown() - s.awaitTermination(5.seconds.dilated) + TestKit.shutdownActorSystem(s) } } } diff --git a/akka-actor-tests/src/test/scala/akka/event/LoggingReceiveSpec.scala b/akka-actor-tests/src/test/scala/akka/event/LoggingReceiveSpec.scala index 5fb2092d86..ee295e6ab0 100644 --- a/akka-actor-tests/src/test/scala/akka/event/LoggingReceiveSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/event/LoggingReceiveSpec.scala @@ -47,9 +47,9 @@ class LoggingReceiveSpec extends WordSpec with BeforeAndAfterEach with BeforeAnd } override def afterAll { - appLogging.shutdown() - appAuto.shutdown() - appLifecycle.shutdown() + TestKit.shutdownActorSystem(appLogging) + TestKit.shutdownActorSystem(appAuto) + TestKit.shutdownActorSystem(appLifecycle) } "A LoggingReceive" must { diff --git a/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala b/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala index 37d46fe743..098be4835d 100644 --- a/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/routing/RoutingSpec.scala @@ -590,7 +590,7 @@ class RoutingSpec extends AkkaSpec(RoutingSpec.config) with DefaultTimeout with try { sys.actorOf(Props.empty.withRouter(FromConfig), "routed") } finally { - sys.shutdown() + shutdown(sys) } } diff --git a/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala b/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala index 06c1b9b9c0..da6e4cd33d 100644 --- a/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala +++ b/akka-actor-tests/src/test/scala/akka/serialization/SerializeSpec.scala @@ -186,7 +186,7 @@ class SerializeSpec extends AkkaSpec(SerializationTests.serializeConf) { (deadLetters eq a.deadLetters) must be(true) } } finally { - a.shutdown() + shutdown(a) } } diff --git a/akka-camel/src/test/java/akka/camel/ConsumerJavaTestBase.java b/akka-camel/src/test/java/akka/camel/ConsumerJavaTestBase.java index 5e9a0d52a1..8e4ca39ddf 100644 --- a/akka-camel/src/test/java/akka/camel/ConsumerJavaTestBase.java +++ b/akka-camel/src/test/java/akka/camel/ConsumerJavaTestBase.java @@ -4,53 +4,50 @@ package akka.camel; +import akka.testkit.AkkaJUnitActorSystemResource; +import akka.testkit.AkkaSpec; +import org.junit.ClassRule; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; -import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.testkit.JavaTestKit; import akka.util.Timeout; import scala.concurrent.Await; import scala.concurrent.ExecutionContext; -import org.junit.AfterClass; import org.junit.Test; import java.util.concurrent.TimeUnit; -import akka.testkit.AkkaSpec; import static org.junit.Assert.*; -/** - * - */ + public class ConsumerJavaTestBase { - static ActorSystem system = ActorSystem.create("test", AkkaSpec.testConf()); + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("ConsumerJavaTest", AkkaSpec.testConf()); - @AfterClass - public static void tearDownAfterClass() { - system.shutdown(); + private final ActorSystem system = actorSystemResource.getSystem(); + + @Test + public void shouldHandleExceptionThrownByActorAndGenerateCustomResponse() throws Exception { + new JavaTestKit(system) {{ + String result = new EventFilter(Exception.class) { + protected String run() { + FiniteDuration duration = Duration.create(1, TimeUnit.SECONDS); + Timeout timeout = new Timeout(duration); + Camel camel = CamelExtension.get(system); + ExecutionContext executionContext = system.dispatcher(); + try { + Await.result( + camel.activationFutureFor(system.actorOf(Props.create(SampleErrorHandlingConsumer.class), "sample-error-handling-consumer"), timeout, executionContext), + duration); + return camel.template().requestBody("direct:error-handler-test-java", "hello", String.class); + } + catch (Exception e) { + return e.getMessage(); + } + } + }.occurrences(1).exec(); + assertEquals("error: hello", result); + }}; } - - @Test - public void shouldHandleExceptionThrownByActorAndGenerateCustomResponse() throws Exception { - new JavaTestKit(system) {{ - String result = new EventFilter(Exception.class) { - protected String run() { - FiniteDuration duration = Duration.create(1, TimeUnit.SECONDS); - Timeout timeout = new Timeout(duration); - Camel camel = CamelExtension.get(system); - ExecutionContext executionContext = system.dispatcher(); - try { - Await.result( - camel.activationFutureFor(system.actorOf(Props.create(SampleErrorHandlingConsumer.class), "sample-error-handling-consumer"), timeout, executionContext), - duration); - return camel.template().requestBody("direct:error-handler-test-java", "hello", String.class); - } - catch (Exception e) { - return e.getMessage(); - } - } - }.occurrences(1).exec(); - assertEquals("error: hello", result); - }}; - } } diff --git a/akka-camel/src/test/java/akka/camel/CustomRouteTestBase.java b/akka-camel/src/test/java/akka/camel/CustomRouteTestBase.java index 6fbd598c59..809466b40f 100644 --- a/akka-camel/src/test/java/akka/camel/CustomRouteTestBase.java +++ b/akka-camel/src/test/java/akka/camel/CustomRouteTestBase.java @@ -4,7 +4,9 @@ import akka.actor.*; import akka.camel.internal.component.CamelPath; import akka.camel.javaapi.UntypedConsumerActor; import akka.camel.javaapi.UntypedProducerActor; +import akka.testkit.AkkaJUnitActorSystemResource; import akka.util.Timeout; +import org.junit.*; import scala.concurrent.Await; import scala.concurrent.ExecutionContext; import scala.concurrent.duration.Duration; @@ -14,25 +16,20 @@ import org.apache.camel.Exchange; import org.apache.camel.Predicate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; -import org.junit.Before; -import org.junit.After; -import org.junit.Test; import java.util.concurrent.TimeUnit; public class CustomRouteTestBase { - private static Camel camel; - private static ActorSystem system; - @Before - public void before() { - system = ActorSystem.create("test"); - camel = (Camel) CamelExtension.get(system); - } + @Rule + public AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("CustomRouteTest"); - @After - public void after() { - system.shutdown(); + private final ActorSystem system = actorSystemResource.getSystem(); + private Camel camel = (Camel) CamelExtension.get(system); + + public static class MyActor extends UntypedActor { + @Override public void onReceive(Object o) {} } @Test @@ -98,7 +95,7 @@ public class CustomRouteTestBase { camel.activationFutureFor(system.actorOf(Props.create(TestAckConsumer.class, "direct:testConsumerAckFromUri","mock:mockAckUri"), "testConsumerAckUri"), timeout, executionContext), duration); - camel.context().addRoutes(new CustomRouteBuilder("direct:testAckFromUri","akka://test/user/testConsumerAckUri?autoAck=false")); + camel.context().addRoutes(new CustomRouteBuilder("direct:testAckFromUri","akka://CustomRouteTest/user/testConsumerAckUri?autoAck=false")); camel.template().sendBody("direct:testAckFromUri", "test"); assertMockEndpoint(mockEndpoint); system.stop(consumer); diff --git a/akka-camel/src/test/java/akka/camel/MessageJavaTestBase.java b/akka-camel/src/test/java/akka/camel/MessageJavaTestBase.java index 3eeb8c4186..7d16712fe1 100644 --- a/akka-camel/src/test/java/akka/camel/MessageJavaTestBase.java +++ b/akka-camel/src/test/java/akka/camel/MessageJavaTestBase.java @@ -6,11 +6,10 @@ package akka.camel; import akka.actor.ActorSystem; import akka.dispatch.Mapper; -import akka.japi.Function; +import akka.testkit.AkkaJUnitActorSystemResource; import org.apache.camel.NoTypeConversionAvailableException; import org.apache.camel.converter.stream.InputStreamCache; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.ClassRule; import org.junit.Test; import java.io.InputStream; @@ -22,112 +21,106 @@ import static org.junit.Assert.assertEquals; * */ public class MessageJavaTestBase { - static Camel camel; - private static ActorSystem system; - private Map empty = new HashMap(); + private Map empty = new HashMap(); - @BeforeClass - public static void setUpBeforeClass() { - system = ActorSystem.create("test"); - camel = (Camel) CamelExtension.get(system); + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("MessageJavaTest"); + + private final ActorSystem system = actorSystemResource.getSystem(); + private Camel camel = (Camel) CamelExtension.get(system); + + CamelMessage message(Object body){ return new CamelMessage(body, new HashMap()); } + CamelMessage message(Object body, Map headers){ return new CamelMessage(body, headers); } + + + @Test public void shouldConvertDoubleBodyToString() { + assertEquals("1.4", message("1.4", empty).getBodyAs(String.class,camel.context())); + } + + @Test(expected=NoTypeConversionAvailableException.class) + public void shouldThrowExceptionWhenConvertingDoubleBodyToInputStream() { + message(1.4).getBodyAs(InputStream.class,camel.context()); + } + + @Test public void shouldConvertDoubleHeaderToString() { + CamelMessage message = message("test" , createMap("test", 1.4)); + assertEquals("1.4", message.getHeaderAs("test", String.class,camel.context())); + } + + @Test public void shouldReturnSubsetOfHeaders() { + CamelMessage message = message("test" , createMap("A", "1", "B", "2")); + assertEquals(createMap("B", "2"), message.getHeaders(createSet("B"))); + } + + @Test(expected=UnsupportedOperationException.class) + public void shouldReturnSubsetOfHeadersUnmodifiable() { + CamelMessage message = message("test" , createMap("A", "1", "B", "2")); + message.getHeaders(createSet("B")).put("x", "y"); + } + + @Test public void shouldReturnAllHeaders() { + CamelMessage message = message("test" , createMap("A", "1", "B", "2")); + assertEquals(createMap("A", "1", "B", "2"), message.getHeaders()); + } + + @Test(expected=UnsupportedOperationException.class) + public void shouldReturnAllHeadersUnmodifiable() { + CamelMessage message = message("test" , createMap("A", "1", "B", "2")); + message.getHeaders().put("x", "y"); + } + + @Test public void shouldTransformBodyAndPreserveHeaders() { + assertEquals( + message("ab", createMap("A", "1")), + message("a" , createMap("A", "1")).mapBody(new TestTransformer())); + } + + @Test public void shouldConvertBodyAndPreserveHeaders() { + assertEquals( + message("1.4", createMap("A", "1")), + message(1.4 , createMap("A", "1")).withBodyAs(String.class,camel.context())); + } + + @Test public void shouldSetBodyAndPreserveHeaders() { + assertEquals( + message("test2" , createMap("A", "1")), + message("test1" , createMap("A", "1")).withBody("test2")); + } + + @Test public void shouldSetHeadersAndPreserveBody() { + assertEquals( + message("test1" , createMap("C", "3")), + message("test1" , createMap("A", "1")).withHeaders(createMap("C", "3"))); + } + + @Test + public void shouldBeAbleToReReadStreamCacheBody() throws Exception { + CamelMessage msg = new CamelMessage(new InputStreamCache("test1".getBytes("utf-8")), empty); + assertEquals("test1", msg.getBodyAs(String.class, camel.context())); + // re-read + assertEquals("test1", msg.getBodyAs(String.class, camel.context())); + } + + private static Set createSet(String... entries) { + HashSet set = new HashSet(); + set.addAll(Arrays.asList(entries)); + return set; + } + + private static Map createMap(Object... pairs) { + HashMap map = new HashMap(); + for (int i = 0; i < pairs.length; i += 2) { + map.put((String)pairs[i], pairs[i+1]); } + return map; + } - @AfterClass - public static void cleanup(){ - system.shutdown(); - } - - CamelMessage message(Object body){ return new CamelMessage(body, new HashMap()); } - CamelMessage message(Object body, Map headers){ return new CamelMessage(body, headers); } - - - @Test public void shouldConvertDoubleBodyToString() { - assertEquals("1.4", message("1.4", empty).getBodyAs(String.class,camel.context())); - } - - @Test(expected=NoTypeConversionAvailableException.class) - public void shouldThrowExceptionWhenConvertingDoubleBodyToInputStream() { - message(1.4).getBodyAs(InputStream.class,camel.context()); - } - - @Test public void shouldConvertDoubleHeaderToString() { - CamelMessage message = message("test" , createMap("test", 1.4)); - assertEquals("1.4", message.getHeaderAs("test", String.class,camel.context())); - } - - @Test public void shouldReturnSubsetOfHeaders() { - CamelMessage message = message("test" , createMap("A", "1", "B", "2")); - assertEquals(createMap("B", "2"), message.getHeaders(createSet("B"))); - } - - @Test(expected=UnsupportedOperationException.class) - public void shouldReturnSubsetOfHeadersUnmodifiable() { - CamelMessage message = message("test" , createMap("A", "1", "B", "2")); - message.getHeaders(createSet("B")).put("x", "y"); - } - - @Test public void shouldReturnAllHeaders() { - CamelMessage message = message("test" , createMap("A", "1", "B", "2")); - assertEquals(createMap("A", "1", "B", "2"), message.getHeaders()); - } - - @Test(expected=UnsupportedOperationException.class) - public void shouldReturnAllHeadersUnmodifiable() { - CamelMessage message = message("test" , createMap("A", "1", "B", "2")); - message.getHeaders().put("x", "y"); - } - - @Test public void shouldTransformBodyAndPreserveHeaders() { - assertEquals( - message("ab", createMap("A", "1")), - message("a" , createMap("A", "1")).mapBody(new TestTransformer())); - } - - @Test public void shouldConvertBodyAndPreserveHeaders() { - assertEquals( - message("1.4", createMap("A", "1")), - message(1.4 , createMap("A", "1")).withBodyAs(String.class,camel.context())); - } - - @Test public void shouldSetBodyAndPreserveHeaders() { - assertEquals( - message("test2" , createMap("A", "1")), - message("test1" , createMap("A", "1")).withBody("test2")); - } - - @Test public void shouldSetHeadersAndPreserveBody() { - assertEquals( - message("test1" , createMap("C", "3")), - message("test1" , createMap("A", "1")).withHeaders(createMap("C", "3"))); - } - - @Test - public void shouldBeAbleToReReadStreamCacheBody() throws Exception { - CamelMessage msg = new CamelMessage(new InputStreamCache("test1".getBytes("utf-8")), empty); - assertEquals("test1", msg.getBodyAs(String.class, camel.context())); - // re-read - assertEquals("test1", msg.getBodyAs(String.class, camel.context())); - } - - private static Set createSet(String... entries) { - HashSet set = new HashSet(); - set.addAll(Arrays.asList(entries)); - return set; - } - - private static Map createMap(Object... pairs) { - HashMap map = new HashMap(); - for (int i = 0; i < pairs.length; i += 2) { - map.put((String)pairs[i], pairs[i+1]); - } - return map; - } - - private static class TestTransformer extends Mapper { - @Override - public String apply(String param) { - return param + "b"; - } + private static class TestTransformer extends Mapper { + @Override + public String apply(String param) { + return param + "b"; } + } } diff --git a/akka-camel/src/test/scala/akka/camel/CamelConfigSpec.scala b/akka-camel/src/test/scala/akka/camel/CamelConfigSpec.scala index 7de26bb1cd..0c90230fb0 100644 --- a/akka-camel/src/test/scala/akka/camel/CamelConfigSpec.scala +++ b/akka-camel/src/test/scala/akka/camel/CamelConfigSpec.scala @@ -8,13 +8,14 @@ import org.scalatest.WordSpec import akka.actor.ActorSystem import scala.concurrent.duration.Duration import java.util.concurrent.TimeUnit._ +import akka.testkit.TestKit class CamelConfigSpec extends WordSpec with MustMatchers { val (settings, config) = { val system = ActorSystem("CamelConfigSpec") val result = (CamelExtension(system).settings, system.settings.config) - system.shutdown() + TestKit.shutdownActorSystem(system) result } "CamelConfigSpec" must { diff --git a/akka-camel/src/test/scala/akka/camel/ProducerFeatureTest.scala b/akka-camel/src/test/scala/akka/camel/ProducerFeatureTest.scala index 43349dc9ed..888ca7fafa 100644 --- a/akka-camel/src/test/scala/akka/camel/ProducerFeatureTest.scala +++ b/akka-camel/src/test/scala/akka/camel/ProducerFeatureTest.scala @@ -31,7 +31,7 @@ class ProducerFeatureTest extends TestKit(ActorSystem("test", AkkaSpec.testConf) override protected def afterAll() { super.afterAll() - system.shutdown() + shutdown(system) } val camelContext = camel.context diff --git a/akka-camel/src/test/scala/akka/camel/TestSupport.scala b/akka-camel/src/test/scala/akka/camel/TestSupport.scala index 55e6b13d53..48bb339334 100644 --- a/akka-camel/src/test/scala/akka/camel/TestSupport.scala +++ b/akka-camel/src/test/scala/akka/camel/TestSupport.scala @@ -15,7 +15,7 @@ import scala.reflect.ClassTag import akka.actor.{ ActorRef, Props, ActorSystem, Actor } import scala.concurrent.Await import akka.util.Timeout -import akka.testkit.AkkaSpec +import akka.testkit.{ TestKit, AkkaSpec } private[camel] object TestSupport { def start(actor: ⇒ Actor, name: String)(implicit system: ActorSystem, timeout: Timeout): ActorRef = @@ -53,7 +53,7 @@ private[camel] object TestSupport { abstract override protected def afterAll() { super.afterAll() - system.shutdown() + TestKit.shutdownActorSystem(system) } } @@ -68,7 +68,7 @@ private[camel] object TestSupport { } override protected def afterEach() { - system.shutdown() + TestKit.shutdownActorSystem(system) super.afterEach() } diff --git a/akka-camel/src/test/scala/akka/camel/internal/ActivationTrackerTest.scala b/akka-camel/src/test/scala/akka/camel/internal/ActivationTrackerTest.scala index 783e7ab9a5..e6bfae740a 100644 --- a/akka-camel/src/test/scala/akka/camel/internal/ActivationTrackerTest.scala +++ b/akka-camel/src/test/scala/akka/camel/internal/ActivationTrackerTest.scala @@ -11,7 +11,7 @@ import akka.camel.internal.ActivationProtocol._ class ActivationTrackerTest extends TestKit(ActorSystem("test")) with WordSpec with MustMatchers with BeforeAndAfterAll with BeforeAndAfterEach with GivenWhenThen { - override protected def afterAll() { system.shutdown() } + override protected def afterAll() { shutdown(system) } var actor: TestProbe = _ var awaiting: Awaiting = _ diff --git a/akka-camel/src/test/scala/akka/camel/internal/component/ActorProducerTest.scala b/akka-camel/src/test/scala/akka/camel/internal/component/ActorProducerTest.scala index 4d729c8790..5124ddeac9 100644 --- a/akka-camel/src/test/scala/akka/camel/internal/component/ActorProducerTest.scala +++ b/akka-camel/src/test/scala/akka/camel/internal/component/ActorProducerTest.scala @@ -379,7 +379,7 @@ private[camel] trait ActorProducerFixture extends MockitoSugar with BeforeAndAft } override protected def afterAll() { - system.shutdown() + shutdown(system) } def msg(s: String) = CamelMessage(s, Map.empty) diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/ClusterDeathWatchSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/ClusterDeathWatchSpec.scala index 8483313589..897a8bc2df 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/ClusterDeathWatchSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/ClusterDeathWatchSpec.scala @@ -251,8 +251,7 @@ abstract class ClusterDeathWatchSpec endProbe.expectMsg(EndActor.EndAck) } finally { - endSystem.shutdown() - endSystem.awaitTermination(10 seconds) + shutdown(endSystem, 10 seconds) } // no barrier here, because it is not part of testConductor roles any more diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartFirstSeedNodeSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartFirstSeedNodeSpec.scala index 469370050d..dcb70fbc8d 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartFirstSeedNodeSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/RestartFirstSeedNodeSpec.scala @@ -57,9 +57,9 @@ abstract class RestartFirstSeedNodeSpec override def afterAll(): Unit = { runOn(seed1) { if (seed1System.isTerminated) - restartedSeed1System.shutdown() + shutdown(restartedSeed1System) else - seed1System.shutdown() + shutdown(seed1System) } super.afterAll() } @@ -103,8 +103,7 @@ abstract class RestartFirstSeedNodeSpec // shutdown seed1System runOn(seed1) { - seed1System.shutdown() - seed1System.awaitTermination(remaining) + shutdown(seed1System, remaining) } runOn(seed2, seed3) { awaitMembersUp(2, canNotBePartOfMemberRing = Set(seedNodes.head)) diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/StressSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/StressSpec.scala index 072b0e1b2f..07804290b9 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/StressSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/StressSpec.scala @@ -961,7 +961,7 @@ abstract class StressSpec reportResult { val nextAS = if (activeRoles contains myself) { - previousAS foreach { _.shutdown() } + previousAS foreach { as ⇒ TestKit.shutdownActorSystem(as) } val sys = ActorSystem(system.name, system.settings.config) muteLog(sys) Cluster(sys).joinSeedNodes(seedNodes.toIndexedSeq map address) @@ -990,7 +990,7 @@ abstract class StressSpec } } - loop(1, None, Set.empty) foreach { _.shutdown } + loop(1, None, Set.empty) foreach { as ⇒ TestKit.shutdownActorSystem(as) } within(loopDuration) { runOn(usedRoles: _*) { awaitMembersUp(nbrUsedRoles, timeout = remaining) diff --git a/akka-cluster/src/multi-jvm/scala/akka/cluster/UnreachableNodeJoinsAgainSpec.scala b/akka-cluster/src/multi-jvm/scala/akka/cluster/UnreachableNodeJoinsAgainSpec.scala index b1247b065a..48aadb8045 100644 --- a/akka-cluster/src/multi-jvm/scala/akka/cluster/UnreachableNodeJoinsAgainSpec.scala +++ b/akka-cluster/src/multi-jvm/scala/akka/cluster/UnreachableNodeJoinsAgainSpec.scala @@ -185,8 +185,7 @@ abstract class UnreachableNodeJoinsAgainSpec endProbe.expectMsg(EndActor.EndAck) } finally { - freshSystem.shutdown() - freshSystem.awaitTermination(10 seconds) + shutdown(freshSystem) } // no barrier here, because it is not part of testConductor roles any more } diff --git a/akka-contrib/src/test/java/akka/contrib/pattern/DistributedPubSubMediatorTest.java b/akka-contrib/src/test/java/akka/contrib/pattern/DistributedPubSubMediatorTest.java index ea2d7b77f9..aa804df969 100644 --- a/akka-contrib/src/test/java/akka/contrib/pattern/DistributedPubSubMediatorTest.java +++ b/akka-contrib/src/test/java/akka/contrib/pattern/DistributedPubSubMediatorTest.java @@ -4,8 +4,8 @@ package akka.contrib.pattern; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; import akka.actor.ActorRef; @@ -17,17 +17,12 @@ import akka.event.LoggingAdapter; public class DistributedPubSubMediatorTest { - private static ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("DistributedPubSubMediatorTest"); - @BeforeClass - public static void setup() { - system = ActorSystem.create(); - } + private final ActorSystem system = actorSystemResource.getSystem(); - @AfterClass - public static void teardown() { - system.shutdown(); - } @Test public void demonstrateUsage() { diff --git a/akka-contrib/src/test/java/akka/contrib/pattern/ReliableProxyTest.java b/akka-contrib/src/test/java/akka/contrib/pattern/ReliableProxyTest.java index 752063921f..c27e97a724 100644 --- a/akka-contrib/src/test/java/akka/contrib/pattern/ReliableProxyTest.java +++ b/akka-contrib/src/test/java/akka/contrib/pattern/ReliableProxyTest.java @@ -4,8 +4,8 @@ package akka.contrib.pattern; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; import scala.concurrent.duration.Duration; @@ -25,17 +25,11 @@ import akka.contrib.pattern.ReliableProxy; public class ReliableProxyTest { - private static ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("ReliableProxyTest"); - @BeforeClass - public static void setup() { - system = ActorSystem.create(); - } - - @AfterClass - public static void teardown() { - system.shutdown(); - } + private final ActorSystem system = actorSystemResource.getSystem(); @Test public void demonstrateUsage() { diff --git a/akka-contrib/src/test/scala/akka/contrib/throttle/TimerBasedThrottlerSpec.scala b/akka-contrib/src/test/scala/akka/contrib/throttle/TimerBasedThrottlerSpec.scala index 7466833f43..0d4a72d8c0 100644 --- a/akka-contrib/src/test/scala/akka/contrib/throttle/TimerBasedThrottlerSpec.scala +++ b/akka-contrib/src/test/scala/akka/contrib/throttle/TimerBasedThrottlerSpec.scala @@ -32,7 +32,7 @@ class TimerBasedThrottlerSpec extends TestKit(ActorSystem("TimerBasedThrottlerSp with WordSpec with MustMatchers with BeforeAndAfterAll { override def afterAll { - system.shutdown() + shutdown(system) } "A throttler" must { diff --git a/akka-docs/rst/general/code/docs/config/ConfigDocSpec.scala b/akka-docs/rst/general/code/docs/config/ConfigDocSpec.scala index 264ed6147b..3a60fcd51f 100644 --- a/akka-docs/rst/general/code/docs/config/ConfigDocSpec.scala +++ b/akka-docs/rst/general/code/docs/config/ConfigDocSpec.scala @@ -5,6 +5,7 @@ package docs.config import org.scalatest.WordSpec import org.scalatest.matchers.MustMatchers +import akka.testkit.TestKit //#imports import akka.actor.ActorSystem @@ -28,6 +29,6 @@ class ConfigDocSpec extends WordSpec with MustMatchers { val system = ActorSystem("MySystem", ConfigFactory.load(customConf)) //#custom-config - system.shutdown() + TestKit.shutdownActorSystem(system) } } diff --git a/akka-docs/rst/java/code/docs/actor/FSMDocTestBase.java b/akka-docs/rst/java/code/docs/actor/FSMDocTestBase.java index 467e012010..bd528381db 100644 --- a/akka-docs/rst/java/code/docs/actor/FSMDocTestBase.java +++ b/akka-docs/rst/java/code/docs/actor/FSMDocTestBase.java @@ -17,6 +17,7 @@ import akka.actor.UntypedActor; import akka.actor.ActorSystem; import akka.actor.Props; +import akka.testkit.JavaTestKit; import akka.testkit.TestProbe; import akka.testkit.AkkaSpec; @@ -201,7 +202,7 @@ public class FSMDocTestBase { @org.junit.After public void cleanup() { - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } } diff --git a/akka-docs/rst/java/code/docs/actor/FaultHandlingTestBase.java b/akka-docs/rst/java/code/docs/actor/FaultHandlingTestBase.java index b2ae8df06c..757cb064a2 100644 --- a/akka-docs/rst/java/code/docs/actor/FaultHandlingTestBase.java +++ b/akka-docs/rst/java/code/docs/actor/FaultHandlingTestBase.java @@ -26,6 +26,7 @@ import akka.testkit.TestProbe; import akka.testkit.ErrorFilter; import akka.testkit.EventFilter; import akka.testkit.TestEvent; +import akka.testkit.JavaTestKit; import static java.util.concurrent.TimeUnit.SECONDS; import static akka.japi.Util.immutableSeq; import akka.japi.Function; @@ -155,7 +156,8 @@ public class FaultHandlingTestBase { @AfterClass public static void cleanup() { - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); + system = null; } @Test diff --git a/akka-docs/rst/java/code/docs/actor/InboxDocTest.java b/akka-docs/rst/java/code/docs/actor/InboxDocTest.java index 900bee998a..780499f22c 100644 --- a/akka-docs/rst/java/code/docs/actor/InboxDocTest.java +++ b/akka-docs/rst/java/code/docs/actor/InboxDocTest.java @@ -6,8 +6,8 @@ package docs.actor; import java.util.concurrent.TimeUnit; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; import scala.concurrent.duration.Duration; @@ -21,19 +21,12 @@ import akka.testkit.JavaTestKit; public class InboxDocTest { - private static ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("InboxDocTest", AkkaSpec.testConf()); - @BeforeClass - public static void beforeAll() { - system = ActorSystem.create("MySystem", AkkaSpec.testConf()); - } + private final ActorSystem system = actorSystemResource.getSystem(); - @AfterClass - public static void afterAll() { - system.shutdown(); - system = null; - } - @Test public void demonstrateInbox() { final JavaTestKit probe = new JavaTestKit(system); diff --git a/akka-docs/rst/java/code/docs/actor/InitializationDocSpecJava.java b/akka-docs/rst/java/code/docs/actor/InitializationDocSpecJava.java index 864a2b7848..525e15c936 100644 --- a/akka-docs/rst/java/code/docs/actor/InitializationDocSpecJava.java +++ b/akka-docs/rst/java/code/docs/actor/InitializationDocSpecJava.java @@ -1,96 +1,86 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ package docs.actor; import akka.actor.*; import akka.japi.Procedure; +import akka.testkit.AkkaJUnitActorSystemResource; import akka.testkit.JavaTestKit; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.ClassRule; import org.junit.Test; import scala.Option; -/** - * Copyright (C) 2009-2013 Typesafe Inc. - */ public class InitializationDocSpecJava { - static public class PreStartInitExample extends UntypedActor { + static public class PreStartInitExample extends UntypedActor { - public void onReceive(Object message) throws Exception {} - - //#preStartInit - @Override - public void preStart() { - // Initialize children here - } - - // Overriding postRestart to disable the call to preStart() - // after restarts - @Override - public void postRestart(Throwable reason) { - } - - // The default implementation of preRestart() stops all the children - // of the actor. To opt-out from stopping the children, we - // have to override preRestart() - @Override - public void preRestart(Throwable reason, Option message) - throws Exception { - // Keep the call to postStop(), but no stopping of children - postStop(); - } - //#preStartInit + public void onReceive(Object message) throws Exception {} + //#preStartInit + @Override + public void preStart() { + // Initialize children here } - public static class MessageInitExample extends UntypedActor { - //#messageInit - private String initializeMe = null; - - @Override - public void onReceive(Object message) throws Exception { - if (message.equals("init")) { - initializeMe = "Up and running"; - getContext().become(new Procedure() { - @Override - public void apply(Object message) throws Exception { - if (message.equals("U OK?")) - getSender().tell(initializeMe, getSelf()); - } - }); - } - } - //#messageInit + // Overriding postRestart to disable the call to preStart() + // after restarts + @Override + public void postRestart(Throwable reason) { } - static ActorSystem system; - - @BeforeClass - public static void setup() { - system = ActorSystem.create("TestSystem"); + // The default implementation of preRestart() stops all the children + // of the actor. To opt-out from stopping the children, we + // have to override preRestart() + @Override + public void preRestart(Throwable reason, Option message) + throws Exception { + // Keep the call to postStop(), but no stopping of children + postStop(); } + //#preStartInit - @AfterClass - public static void teardown() { - system.shutdown(); + } + + public static class MessageInitExample extends UntypedActor { + //#messageInit + private String initializeMe = null; + + @Override + public void onReceive(Object message) throws Exception { + if (message.equals("init")) { + initializeMe = "Up and running"; + getContext().become(new Procedure() { + @Override + public void apply(Object message) throws Exception { + if (message.equals("U OK?")) + getSender().tell(initializeMe, getSelf()); + } + }); + } } + //#messageInit + } - @Test - public void testIt() { + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("InitializationDocSpecJava"); - new JavaTestKit(system) {{ - ActorRef testactor = system.actorOf(Props.create(MessageInitExample.class), "testactor"); - String probe = "U OK?"; + private final ActorSystem system = actorSystemResource.getSystem(); - testactor.tell(probe, getRef()); - expectNoMsg(); + @Test + public void testIt() { - testactor.tell("init", getRef()); - testactor.tell(probe, getRef()); - expectMsgEquals("Up and running"); - }}; + new JavaTestKit(system) {{ + ActorRef testactor = system.actorOf(Props.create(MessageInitExample.class), "testactor"); + String probe = "U OK?"; + testactor.tell(probe, getRef()); + expectNoMsg(); - - } - + testactor.tell("init", getRef()); + testactor.tell(probe, getRef()); + expectMsgEquals("Up and running"); + }}; + } } diff --git a/akka-docs/rst/java/code/docs/actor/SchedulerDocTestBase.java b/akka-docs/rst/java/code/docs/actor/SchedulerDocTestBase.java index ac2e8c5f87..eb38be10e0 100644 --- a/akka-docs/rst/java/code/docs/actor/SchedulerDocTestBase.java +++ b/akka-docs/rst/java/code/docs/actor/SchedulerDocTestBase.java @@ -17,26 +17,17 @@ import akka.actor.Cancellable; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.testkit.AkkaSpec; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.*; public class SchedulerDocTestBase { - ActorSystem system; - ActorRef testActor; + @Rule + public AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("SchedulerDocTest", AkkaSpec.testConf()); - @Before - public void setUp() { - system = ActorSystem.create("MySystem", AkkaSpec.testConf()); - testActor = system.actorOf(Props.create(MyUntypedActor.class)); - } - - @After - public void tearDown() { - system.shutdown(); - } + private final ActorSystem system = actorSystemResource.getSystem(); + private ActorRef testActor = system.actorOf(Props.create(MyUntypedActor.class)); @Test public void scheduleOneOffTask() { diff --git a/akka-docs/rst/java/code/docs/actor/UntypedActorDocTestBase.java b/akka-docs/rst/java/code/docs/actor/UntypedActorDocTestBase.java index f58f1b82cf..e49a89acf8 100644 --- a/akka-docs/rst/java/code/docs/actor/UntypedActorDocTestBase.java +++ b/akka-docs/rst/java/code/docs/actor/UntypedActorDocTestBase.java @@ -15,8 +15,8 @@ import java.util.ArrayList; import java.util.Iterator; import java.util.concurrent.TimeUnit; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; //#import-gracefulStop @@ -82,18 +82,11 @@ import akka.util.Timeout; public class UntypedActorDocTestBase { - private static ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("UntypedActorDocTest", AkkaSpec.testConf()); - @BeforeClass - public static void beforeAll() { - system = ActorSystem.create("MySystem", AkkaSpec.testConf()); - } - - @AfterClass - public static void afterAll() { - system.shutdown(); - system = null; - } + private final ActorSystem system = actorSystemResource.getSystem(); @SuppressWarnings("unused") @Test @@ -156,7 +149,7 @@ public class UntypedActorDocTestBase { } }; } finally { - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } } diff --git a/akka-docs/rst/java/code/docs/actor/mailbox/DurableMailboxDocTestBase.java b/akka-docs/rst/java/code/docs/actor/mailbox/DurableMailboxDocTestBase.java index 3d00624b3a..6f9c75ed89 100644 --- a/akka-docs/rst/java/code/docs/actor/mailbox/DurableMailboxDocTestBase.java +++ b/akka-docs/rst/java/code/docs/actor/mailbox/DurableMailboxDocTestBase.java @@ -9,8 +9,8 @@ import akka.actor.ActorRef; //#imports -import org.junit.After; -import org.junit.Before; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; import akka.testkit.AkkaSpec; @@ -20,18 +20,12 @@ import akka.actor.UntypedActor; public class DurableMailboxDocTestBase { - ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("DurableMailboxDocTest", + ConfigFactory.parseString(DurableMailboxDocSpec.config()).withFallback(AkkaSpec.testConf())); - @Before - public void setUp() { - system = ActorSystem.create("MySystem", - ConfigFactory.parseString(DurableMailboxDocSpec.config()).withFallback(AkkaSpec.testConf())); - } - - @After - public void tearDown() { - system.shutdown(); - } + private final ActorSystem system = actorSystemResource.getSystem(); @Test public void configDefinedDispatcher() { diff --git a/akka-docs/rst/java/code/docs/agent/AgentDocTest.java b/akka-docs/rst/java/code/docs/agent/AgentDocTest.java index 3c5883d384..662401cbfa 100644 --- a/akka-docs/rst/java/code/docs/agent/AgentDocTest.java +++ b/akka-docs/rst/java/code/docs/agent/AgentDocTest.java @@ -5,10 +5,7 @@ package docs.agent; import static org.junit.Assert.*; -import org.junit.AfterClass; -import org.junit.BeforeClass; import org.junit.Test; -import akka.testkit.AkkaSpec; import scala.concurrent.Await; import scala.concurrent.duration.Duration; diff --git a/akka-docs/rst/java/code/docs/camel/ActivationTestBase.java b/akka-docs/rst/java/code/docs/camel/ActivationTestBase.java index 7a827d86da..405aa09a63 100644 --- a/akka-docs/rst/java/code/docs/camel/ActivationTestBase.java +++ b/akka-docs/rst/java/code/docs/camel/ActivationTestBase.java @@ -6,6 +6,8 @@ package docs.camel; import akka.camel.Camel; import akka.camel.CamelExtension; import akka.camel.javaapi.UntypedConsumerActor; + import akka.testkit.JavaTestKit; + import akka.testkit.TestKit; import akka.util.Timeout; import scala.concurrent.Future; import scala.concurrent.duration.Duration; @@ -38,7 +40,7 @@ public class ActivationTestBase { Future deactivationFuture = camel.deactivationFutureFor(producer, timeout, system.dispatcher()); //#CamelDeactivation - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } public static class MyConsumer extends UntypedConsumerActor { diff --git a/akka-docs/rst/java/code/docs/camel/CamelExtensionTestBase.java b/akka-docs/rst/java/code/docs/camel/CamelExtensionTestBase.java index b9b6337ef7..664ed04bbf 100644 --- a/akka-docs/rst/java/code/docs/camel/CamelExtensionTestBase.java +++ b/akka-docs/rst/java/code/docs/camel/CamelExtensionTestBase.java @@ -3,6 +3,7 @@ package docs.camel; import akka.actor.ActorSystem; import akka.camel.Camel; import akka.camel.CamelExtension; +import akka.testkit.JavaTestKit; import org.apache.camel.CamelContext; import org.apache.camel.ProducerTemplate; import org.junit.Test; @@ -16,7 +17,7 @@ public class CamelExtensionTestBase { CamelContext camelContext = camel.context(); ProducerTemplate producerTemplate = camel.template(); //#CamelExtension - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } public void addActiveMQComponent() { //#CamelExtensionAddComponent @@ -26,7 +27,7 @@ public class CamelExtensionTestBase { // camelContext.addComponent("activemq", ActiveMQComponent.activeMQComponent( // "vm://localhost?broker.persistent=false")); //#CamelExtensionAddComponent - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } } diff --git a/akka-docs/rst/java/code/docs/camel/CustomRouteTestBase.java b/akka-docs/rst/java/code/docs/camel/CustomRouteTestBase.java index 8393ac4c9e..2030ca3368 100644 --- a/akka-docs/rst/java/code/docs/camel/CustomRouteTestBase.java +++ b/akka-docs/rst/java/code/docs/camel/CustomRouteTestBase.java @@ -5,6 +5,7 @@ import akka.actor.ActorSystem; import akka.actor.Props; import akka.camel.Camel; import akka.camel.CamelExtension; +import akka.testkit.JavaTestKit; public class CustomRouteTestBase { public void customRoute() throws Exception{ @@ -15,6 +16,6 @@ public class CustomRouteTestBase { camel.context().addRoutes(new CustomRouteBuilder(responder)); //#CustomRoute system.stop(responder); - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } } diff --git a/akka-docs/rst/java/code/docs/camel/OnRouteResponseTestBase.java b/akka-docs/rst/java/code/docs/camel/OnRouteResponseTestBase.java index 832d2c0bba..d547acb12c 100644 --- a/akka-docs/rst/java/code/docs/camel/OnRouteResponseTestBase.java +++ b/akka-docs/rst/java/code/docs/camel/OnRouteResponseTestBase.java @@ -1,6 +1,7 @@ package docs.camel; import akka.actor.*; +import akka.testkit.JavaTestKit; public class OnRouteResponseTestBase { @@ -17,6 +18,6 @@ public class OnRouteResponseTestBase { //#RouteResponse system.stop(receiver); system.stop(forwardResponse); - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } } diff --git a/akka-docs/rst/java/code/docs/camel/ProducerTestBase.java b/akka-docs/rst/java/code/docs/camel/ProducerTestBase.java index 503f470d72..9db7879fea 100644 --- a/akka-docs/rst/java/code/docs/camel/ProducerTestBase.java +++ b/akka-docs/rst/java/code/docs/camel/ProducerTestBase.java @@ -3,6 +3,7 @@ package docs.camel; import java.util.HashMap; import java.util.Map; +import akka.testkit.JavaTestKit; import scala.concurrent.Future; import akka.actor.ActorRef; import akka.actor.ActorSystem; @@ -18,7 +19,7 @@ public class ProducerTestBase { ActorRef producer = system.actorOf(props, "jmsproducer"); producer.tell("", null); //#TellProducer - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } @SuppressWarnings("unused") @@ -30,7 +31,7 @@ public class ProducerTestBase { Future future = Patterns.ask(producer, "some request", 1000); //#AskProducer system.stop(producer); - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } public void correlate(){ @@ -44,6 +45,6 @@ public class ProducerTestBase { "itemId=\"12345\"/>",headers), null); //#Correlate system.stop(producer); - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } } diff --git a/akka-docs/rst/java/code/docs/dispatcher/DispatcherDocTestBase.java b/akka-docs/rst/java/code/docs/dispatcher/DispatcherDocTestBase.java index 6fd18d535a..60e7e70720 100644 --- a/akka-docs/rst/java/code/docs/dispatcher/DispatcherDocTestBase.java +++ b/akka-docs/rst/java/code/docs/dispatcher/DispatcherDocTestBase.java @@ -16,7 +16,9 @@ import akka.event.LoggingAdapter; //#imports-prio-mailbox import akka.dispatch.PriorityGenerator; import akka.dispatch.UnboundedPriorityMailbox; +import akka.testkit.AkkaJUnitActorSystemResource; import akka.testkit.JavaTestKit; +import akka.testkit.TestKit; import com.typesafe.config.Config; //#imports-prio-mailbox @@ -35,8 +37,7 @@ import java.util.concurrent.ConcurrentLinkedQueue; //#imports-required-mailbox import docs.actor.MyBoundedUntypedActor; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.ClassRule; import org.junit.Test; import scala.Option; import scala.concurrent.ExecutionContext; @@ -48,20 +49,13 @@ import akka.testkit.AkkaSpec; public class DispatcherDocTestBase { - static ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("DispatcherDocTest", ConfigFactory.parseString( + DispatcherDocSpec.javaConfig()).withFallback(ConfigFactory.parseString( + DispatcherDocSpec.config())).withFallback(AkkaSpec.testConf())); - @BeforeClass - public static void beforeAll() { - system = ActorSystem.create("MySystem", - ConfigFactory.parseString(DispatcherDocSpec.javaConfig()).withFallback( - ConfigFactory.parseString(DispatcherDocSpec.config())).withFallback(AkkaSpec.testConf())); - } - - @AfterClass - public static void afterAll() { - system.shutdown(); - system = null; - } + private final ActorSystem system = actorSystemResource.getSystem(); @SuppressWarnings("unused") @Test diff --git a/akka-docs/rst/java/code/docs/event/LoggingDocTestBase.java b/akka-docs/rst/java/code/docs/event/LoggingDocTestBase.java index efebb4a291..8dee6b11b6 100644 --- a/akka-docs/rst/java/code/docs/event/LoggingDocTestBase.java +++ b/akka-docs/rst/java/code/docs/event/LoggingDocTestBase.java @@ -19,7 +19,7 @@ import akka.event.Logging.Debug; //#imports-listener import org.junit.Test; - +import akka.testkit.JavaTestKit; import scala.Option; //#imports-deadletter @@ -37,7 +37,7 @@ public class LoggingDocTestBase { ActorSystem system = ActorSystem.create("MySystem"); ActorRef myActor = system.actorOf(Props.create(MyActor.class, this)); myActor.tell("test", null); - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } @Test @@ -47,7 +47,7 @@ public class LoggingDocTestBase { final ActorRef actor = system.actorOf(Props.create(DeadLetterActor.class)); system.eventStream().subscribe(actor, DeadLetter.class); //#deadletters - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } @Test @@ -57,7 +57,7 @@ public class LoggingDocTestBase { final Object[] args = new Object[] { "The", "brown", "fox", "jumps", 42 }; system.log().debug("five parameters: {}, {}, {}, {}, {}", args); //#array - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } //#my-actor diff --git a/akka-docs/rst/java/code/docs/future/FutureDocTestBase.java b/akka-docs/rst/java/code/docs/future/FutureDocTestBase.java index 849504e62f..12860bce92 100644 --- a/akka-docs/rst/java/code/docs/future/FutureDocTestBase.java +++ b/akka-docs/rst/java/code/docs/future/FutureDocTestBase.java @@ -51,8 +51,8 @@ import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import org.junit.After; -import org.junit.Before; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; import akka.testkit.AkkaSpec; @@ -67,45 +67,39 @@ import static org.junit.Assert.*; public class FutureDocTestBase { - ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("FutureDocTest", AkkaSpec.testConf()); - @Before - public void setUp() { - system = ActorSystem.create("MySystem", AkkaSpec.testConf()); - } - - @After - public void tearDown() { - system.shutdown(); - } + private final ActorSystem system = actorSystemResource.getSystem(); public final static class PrintResult extends OnSuccess { - @Override public final void onSuccess(T t) { - // print t - } + @Override public final void onSuccess(T t) { + // print t } + } public final static class Demo { - //#print-result - public final static class PrintResult extends OnSuccess { - @Override public final void onSuccess(T t) { - System.out.println(t); - } + //#print-result + public final static class PrintResult extends OnSuccess { + @Override public final void onSuccess(T t) { + System.out.println(t); } - //#print-result + } + //#print-result } @SuppressWarnings("unchecked") @Test public void useCustomExecutionContext() throws Exception { - ExecutorService yourExecutorServiceGoesHere = Executors.newSingleThreadExecutor(); - //#diy-execution-context - ExecutionContext ec = - ExecutionContexts.fromExecutorService(yourExecutorServiceGoesHere); + ExecutorService yourExecutorServiceGoesHere = Executors.newSingleThreadExecutor(); + //#diy-execution-context + ExecutionContext ec = + ExecutionContexts.fromExecutorService(yourExecutorServiceGoesHere); - //Use ec with your Futures - Future f1 = Futures.successful("foo"); + //Use ec with your Futures + Future f1 = Futures.successful("foo"); - // Then you shut down the ExecutorService at the end of your application. - yourExecutorServiceGoesHere.shutdown(); - //#diy-execution-context + // Then you shut down the ExecutorService at the end of your application. + yourExecutorServiceGoesHere.shutdown(); + //#diy-execution-context } @Test @@ -134,8 +128,8 @@ public class FutureDocTestBase { f.onSuccess(new PrintResult(), system.dispatcher()); //#future-eval - String result = (String) Await.result(f, Duration.create(5, SECONDS)); - assertEquals("HelloWorld", result); + String result = (String) Await.result(f, Duration.create(5, SECONDS)); + assertEquals("HelloWorld", result); } @Test @@ -504,13 +498,13 @@ public class FutureDocTestBase { final ExecutionContext ec = system.dispatcher(); future.onComplete(new OnComplete() { - public void onComplete(Throwable failure, String result) { - if (failure != null) { - //We got a failure, handle it here - } else { - // We got a result, do something with it - } + public void onComplete(Throwable failure, String result) { + if (failure != null) { + //We got a failure, handle it here + } else { + // We got a result, do something with it } + } }, ec); //#onComplete } diff --git a/akka-docs/rst/java/code/docs/io/UdpConnectedDocTest.java b/akka-docs/rst/java/code/docs/io/UdpConnectedDocTest.java index c0aff89891..d43dce153f 100644 --- a/akka-docs/rst/java/code/docs/io/UdpConnectedDocTest.java +++ b/akka-docs/rst/java/code/docs/io/UdpConnectedDocTest.java @@ -4,8 +4,8 @@ package docs.io; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; import akka.actor.ActorSystem; @@ -27,6 +27,7 @@ public class UdpConnectedDocTest { static public class Demo extends UntypedActor { ActorRef connectionActor = null; ActorRef handler = getSelf(); + ActorSystem system = context().system(); @Override public void onReceive(Object msg) { @@ -78,18 +79,6 @@ public class UdpConnectedDocTest { } } - static ActorSystem system; - - @BeforeClass - static public void setup() { - system = ActorSystem.create("UdpConnectedDocTest"); - } - - @AfterClass - static public void teardown() { - system.shutdown(); - } - @Test public void demonstrateConnect() { } diff --git a/akka-docs/rst/java/code/docs/io/UdpDocTest.java b/akka-docs/rst/java/code/docs/io/UdpDocTest.java index d1a7cd91ba..5b61d3b21f 100644 --- a/akka-docs/rst/java/code/docs/io/UdpDocTest.java +++ b/akka-docs/rst/java/code/docs/io/UdpDocTest.java @@ -19,83 +19,73 @@ import java.util.ArrayList; import java.util.List; //#imports -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; public class UdpDocTest { - static public class Demo extends UntypedActor { - public void onReceive(Object message) { - //#manager - final ActorRef udp = Udp.get(system).manager(); - //#manager + static public class Demo extends UntypedActor { + ActorSystem system = context().system(); - //#simplesend - udp.tell(UdpMessage.simpleSender(), getSelf()); + public void onReceive(Object message) { + //#manager + final ActorRef udp = Udp.get(system).manager(); + //#manager - // ... or with socket options: - final List options = new ArrayList(); - options.add(UdpSO.broadcast(true)); - udp.tell(UdpMessage.simpleSender(), getSelf()); - //#simplesend + //#simplesend + udp.tell(UdpMessage.simpleSender(), getSelf()); - ActorRef simpleSender = null; + // ... or with socket options: + final List options = new ArrayList(); + options.add(UdpSO.broadcast(true)); + udp.tell(UdpMessage.simpleSender(), getSelf()); + //#simplesend - //#simplesend-finish - if (message instanceof Udp.SimpleSendReady) { - simpleSender = getSender(); - } - //#simplesend-finish + ActorRef simpleSender = null; - final ByteString data = ByteString.empty(); + //#simplesend-finish + if (message instanceof Udp.SimpleSendReady) { + simpleSender = getSender(); + } + //#simplesend-finish - //#simplesend-send - simpleSender.tell(UdpMessage.send(data, new InetSocketAddress("127.0.0.1", 7654)), getSelf()); - //#simplesend-send + final ByteString data = ByteString.empty(); - final ActorRef handler = getSelf(); + //#simplesend-send + simpleSender.tell(UdpMessage.send(data, new InetSocketAddress("127.0.0.1", 7654)), getSelf()); + //#simplesend-send - //#bind - udp.tell(UdpMessage.bind(handler, new InetSocketAddress("127.0.0.1", 9876)), getSelf()); - //#bind + final ActorRef handler = getSelf(); - ActorRef udpWorker = null; + //#bind + udp.tell(UdpMessage.bind(handler, new InetSocketAddress("127.0.0.1", 9876)), getSelf()); + //#bind - //#bind-finish - if (message instanceof Udp.Bound) { - udpWorker = getSender(); - } - //#bind-finish + ActorRef udpWorker = null; - //#bind-receive - if (message instanceof Udp.Received) { - final Udp.Received rcvd = (Udp.Received) message; - final ByteString payload = rcvd.data(); - final InetSocketAddress sender = rcvd.sender(); - } - //#bind-receive + //#bind-finish + if (message instanceof Udp.Bound) { + udpWorker = getSender(); + } + //#bind-finish - //#bind-send - udpWorker.tell(UdpMessage.send(data, new InetSocketAddress("127.0.0.1", 7654)), getSelf()); - //#bind-send - } + //#bind-receive + if (message instanceof Udp.Received) { + final Udp.Received rcvd = (Udp.Received) message; + final ByteString payload = rcvd.data(); + final InetSocketAddress sender = rcvd.sender(); + } + //#bind-receive + + //#bind-send + udpWorker.tell(UdpMessage.send(data, new InetSocketAddress("127.0.0.1", 7654)), getSelf()); + //#bind-send } + } - static ActorSystem system; - - @BeforeClass - static public void setup() { - system = ActorSystem.create("IODocTest"); - } - - @AfterClass - static public void teardown() { - system.shutdown(); - } - - @Test - public void demonstrateConnect() { - } + @Test + public void demonstrateConnect() { + } } diff --git a/akka-docs/rst/java/code/docs/io/japi/IODocTest.java b/akka-docs/rst/java/code/docs/io/japi/IODocTest.java index fd34917a3a..cec22b6805 100644 --- a/akka-docs/rst/java/code/docs/io/japi/IODocTest.java +++ b/akka-docs/rst/java/code/docs/io/japi/IODocTest.java @@ -5,8 +5,8 @@ package docs.io.japi; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; //#imports @@ -138,19 +138,13 @@ public class IODocTest { } //#client - - private static ActorSystem system; - - @BeforeClass - public static void setup() { - system = ActorSystem.create("IODocTest", AkkaSpec.testConf()); - } - - @AfterClass - public static void teardown() { - system.shutdown(); - } - + + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("IODocTest", AkkaSpec.testConf()); + + private final ActorSystem system = actorSystemResource.getSystem(); + @Test public void testConnection() { new JavaTestKit(system) { diff --git a/akka-docs/rst/java/code/docs/io/japi/PipelineTest.java b/akka-docs/rst/java/code/docs/io/japi/PipelineTest.java index 2f40ef7ff7..bbce4391f8 100644 --- a/akka-docs/rst/java/code/docs/io/japi/PipelineTest.java +++ b/akka-docs/rst/java/code/docs/io/japi/PipelineTest.java @@ -7,8 +7,8 @@ package docs.io.japi; import java.nio.ByteOrder; import java.util.concurrent.TimeUnit; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; import scala.concurrent.duration.Duration; @@ -48,18 +48,12 @@ public class PipelineTest { } final Context ctx = new Context(); //#byteorder - - static ActorSystem system = null; - - @BeforeClass - public static void setup() { - system = ActorSystem.create("PipelineTest"); - } - - @AfterClass - public static void teardown() { - system.shutdown(); - } + + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("PipelineTest"); + + private final ActorSystem system = actorSystemResource.getSystem(); @Test public void demonstratePipeline() throws Exception { diff --git a/akka-docs/rst/java/code/docs/io/japi/SslDocTest.java b/akka-docs/rst/java/code/docs/io/japi/SslDocTest.java index 4d0cd6d79b..956507a323 100644 --- a/akka-docs/rst/java/code/docs/io/japi/SslDocTest.java +++ b/akka-docs/rst/java/code/docs/io/japi/SslDocTest.java @@ -9,8 +9,8 @@ import java.net.InetSocketAddress; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLEngine; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; import akka.actor.ActorContext; @@ -184,17 +184,11 @@ public class SslDocTest { } //#server - private static ActorSystem system; - - @BeforeClass - public static void setup() { - system = ActorSystem.create("IODocTest", AkkaSpec.testConf()); - } - - @AfterClass - public static void teardown() { - system.shutdown(); - } + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("SslDocTest", AkkaSpec.testConf()); + + private final ActorSystem system = actorSystemResource.getSystem(); @Test public void demonstrateSslClient() { diff --git a/akka-docs/rst/java/code/docs/jrouting/ConsistentHashingRouterDocTestBase.java b/akka-docs/rst/java/code/docs/jrouting/ConsistentHashingRouterDocTestBase.java index 901ba33b6e..bb6f16c923 100644 --- a/akka-docs/rst/java/code/docs/jrouting/ConsistentHashingRouterDocTestBase.java +++ b/akka-docs/rst/java/code/docs/jrouting/ConsistentHashingRouterDocTestBase.java @@ -3,8 +3,8 @@ */ package docs.jrouting; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; import akka.testkit.JavaTestKit; import akka.actor.ActorSystem; @@ -27,17 +27,11 @@ import akka.routing.ConsistentHashingRouter.ConsistentHashableEnvelope; public class ConsistentHashingRouterDocTestBase { - static ActorSystem system; - - @BeforeClass - public static void setup() { - system = ActorSystem.create(); - } - - @AfterClass - public static void teardown() { - system.shutdown(); - } + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("ConsistentHashingRouterDocTest"); + + private final ActorSystem system = actorSystemResource.getSystem(); static //#cache-actor diff --git a/akka-docs/rst/java/code/docs/jrouting/CustomRouterDocTestBase.java b/akka-docs/rst/java/code/docs/jrouting/CustomRouterDocTestBase.java index 593ea1ed4f..8e4f3eb024 100644 --- a/akka-docs/rst/java/code/docs/jrouting/CustomRouterDocTestBase.java +++ b/akka-docs/rst/java/code/docs/jrouting/CustomRouterDocTestBase.java @@ -14,9 +14,8 @@ import java.util.Arrays; import java.util.Collections; import java.util.List; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.*; import scala.concurrent.Await; import scala.concurrent.Future; @@ -38,17 +37,11 @@ import akka.util.Timeout; public class CustomRouterDocTestBase { - ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("CustomRouterDocTest", AkkaSpec.testConf()); - @Before - public void setUp() { - system = ActorSystem.create("MySystem", AkkaSpec.testConf()); - } - - @After - public void tearDown() { - system.shutdown(); - } + private final ActorSystem system = actorSystemResource.getSystem(); public static class MyActor extends UntypedActor { @Override public void onReceive(Object o) {} diff --git a/akka-docs/rst/java/code/docs/jrouting/RouterViaProgramDocTestBase.java b/akka-docs/rst/java/code/docs/jrouting/RouterViaProgramDocTestBase.java index ac522d9726..d1bc28a8d8 100644 --- a/akka-docs/rst/java/code/docs/jrouting/RouterViaProgramDocTestBase.java +++ b/akka-docs/rst/java/code/docs/jrouting/RouterViaProgramDocTestBase.java @@ -5,8 +5,8 @@ package docs.jrouting; import java.util.Arrays; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; import akka.actor.ActorRef; @@ -23,17 +23,11 @@ import docs.routing.RouterViaProgramDocSpec.Echo; public class RouterViaProgramDocTestBase { - static ActorSystem system; - - @BeforeClass - public static void setup() { - system = ActorSystem.create(); - } - - @AfterClass - public static void teardown() { - system.shutdown(); - } + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("RouterViaProgramDocTest"); + + private final ActorSystem system = actorSystemResource.getSystem(); private static class JavaTestKitWithSelf extends JavaTestKit { public JavaTestKitWithSelf(ActorSystem system) { diff --git a/akka-docs/rst/java/code/docs/pattern/SchedulerPatternTest.java b/akka-docs/rst/java/code/docs/pattern/SchedulerPatternTest.java index 4d48f89b0c..96f28886e7 100644 --- a/akka-docs/rst/java/code/docs/pattern/SchedulerPatternTest.java +++ b/akka-docs/rst/java/code/docs/pattern/SchedulerPatternTest.java @@ -16,17 +16,11 @@ import java.util.concurrent.TimeUnit; public class SchedulerPatternTest { - static ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("SchedulerPatternTest", AkkaSpec.testConf()); - @BeforeClass - public static void setUp() { - system = ActorSystem.create("SchedulerPatternTest", AkkaSpec.testConf()); - } - - @AfterClass - public static void tearDown() { - system.shutdown(); - } + private final ActorSystem system = actorSystemResource.getSystem(); static //#schedule-constructor diff --git a/akka-docs/rst/java/code/docs/remoting/RemoteDeploymentDocTestBase.java b/akka-docs/rst/java/code/docs/remoting/RemoteDeploymentDocTestBase.java index b4ca288753..16bb803b3f 100644 --- a/akka-docs/rst/java/code/docs/remoting/RemoteDeploymentDocTestBase.java +++ b/akka-docs/rst/java/code/docs/remoting/RemoteDeploymentDocTestBase.java @@ -3,8 +3,8 @@ */ package docs.remoting; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.AkkaJUnitActorSystemResource; +import org.junit.ClassRule; import org.junit.Test; import com.typesafe.config.ConfigFactory; @@ -28,18 +28,12 @@ public class RemoteDeploymentDocTestBase { getSender().tell(getSelf(), getSelf()); } } - - static ActorSystem system; - - @BeforeClass - public static void init() { - system = ActorSystem.create(); - } - - @AfterClass - public static void cleanup() { - system.shutdown(); - } + + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("RemoteDeploymentDocTest"); + + private final ActorSystem system = actorSystemResource.getSystem(); @Test public void demonstrateDeployment() { diff --git a/akka-docs/rst/java/code/docs/serialization/SerializationDocTestBase.java b/akka-docs/rst/java/code/docs/serialization/SerializationDocTestBase.java index b84417d455..f9c514bc7b 100644 --- a/akka-docs/rst/java/code/docs/serialization/SerializationDocTestBase.java +++ b/akka-docs/rst/java/code/docs/serialization/SerializationDocTestBase.java @@ -3,6 +3,7 @@ */ package docs.serialization; +import akka.testkit.JavaTestKit; import org.junit.Test; import static org.junit.Assert.*; //#imports @@ -66,7 +67,7 @@ public class SerializationDocTestBase { final ActorRef deserializedActorRef = extendedSystem.provider().resolveActorRef(identifier); // Then just use the ActorRef //#actorref-serializer - extendedSystem.shutdown(); + JavaTestKit.shutdownActorSystem(extendedSystem); } static @@ -187,6 +188,6 @@ public class SerializationDocTestBase { assertEquals(original, back); //#programmatic - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); } } diff --git a/akka-docs/rst/java/code/docs/testkit/TestKitDocTest.java b/akka-docs/rst/java/code/docs/testkit/TestKitDocTest.java index 69a20e83f9..eabdd17e65 100644 --- a/akka-docs/rst/java/code/docs/testkit/TestKitDocTest.java +++ b/akka-docs/rst/java/code/docs/testkit/TestKitDocTest.java @@ -5,12 +5,12 @@ package docs.testkit; import static org.junit.Assert.*; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import akka.testkit.*; +import docs.actor.mailbox.DurableMailboxDocSpec; +import org.junit.ClassRule; import org.junit.Test; import com.typesafe.config.ConfigFactory; -import com.typesafe.config.Config; import akka.actor.ActorKilledException; import akka.actor.ActorRef; @@ -22,15 +22,18 @@ import akka.actor.Terminated; import akka.actor.UntypedActor; import scala.concurrent.Await; import scala.concurrent.Future; -import akka.testkit.CallingThreadDispatcher; -import akka.testkit.TestActor; import akka.testkit.TestActor.AutoPilot; -import akka.testkit.TestActorRef; -import akka.testkit.JavaTestKit; import scala.concurrent.duration.Duration; public class TestKitDocTest { + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("TestKitDocTest", + ConfigFactory.parseString("akka.loggers = [akka.testkit.TestEventListener]")); + + private final ActorSystem system = actorSystemResource.getSystem(); + //#test-actor-ref static class MyActor extends UntypedActor { public void onReceive(Object o) throws Exception { @@ -43,23 +46,6 @@ public class TestKitDocTest { public boolean testMe() { return true; } } - //#test-actor-ref - - private static ActorSystem system; - - @BeforeClass - public static void setup() { - final Config config = ConfigFactory.parseString( - "akka.loggers = [akka.testkit.TestEventListener]"); - system = ActorSystem.create("demoSystem", config); - } - - @AfterClass - public static void cleanup() { - system.shutdown(); - } - - //#test-actor-ref @Test public void demonstrateTestActorRef() { final Props props = Props.create(MyActor.class); @@ -415,7 +401,7 @@ public class TestKitDocTest { public void demonstrateEventFilter() { //#test-event-filter new JavaTestKit(system) {{ - assertEquals("demoSystem", system.name()); + assertEquals("TestKitDocTest", system.name()); final ActorRef victim = system.actorOf(Props.empty(), "victim"); final int result = new EventFilter(ActorKilledException.class) { @@ -423,7 +409,7 @@ public class TestKitDocTest { victim.tell(Kill.getInstance(), null); return 42; } - }.from("akka://demoSystem/user/victim").occurrences(1).exec(); + }.from("akka://TestKitDocTest/user/victim").occurrences(1).exec(); assertEquals(42, result); }}; diff --git a/akka-docs/rst/java/code/docs/testkit/TestKitSampleTest.java b/akka-docs/rst/java/code/docs/testkit/TestKitSampleTest.java index 7070640d63..09ea85a53a 100644 --- a/akka-docs/rst/java/code/docs/testkit/TestKitSampleTest.java +++ b/akka-docs/rst/java/code/docs/testkit/TestKitSampleTest.java @@ -43,7 +43,8 @@ public class TestKitSampleTest { @AfterClass public static void teardown() { - system.shutdown(); + JavaTestKit.shutdownActorSystem(system); + system = null; } @Test diff --git a/akka-docs/rst/java/code/docs/transactor/TransactorDocTest.java b/akka-docs/rst/java/code/docs/transactor/TransactorDocTest.java index 265b09750e..4797842c57 100644 --- a/akka-docs/rst/java/code/docs/transactor/TransactorDocTest.java +++ b/akka-docs/rst/java/code/docs/transactor/TransactorDocTest.java @@ -5,6 +5,8 @@ package docs.transactor; import static org.junit.Assert.*; + +import akka.testkit.JavaTestKit; import org.junit.Test; //#imports @@ -18,83 +20,83 @@ import static java.util.concurrent.TimeUnit.SECONDS; public class TransactorDocTest { - @Test - public void coordinatedExample() throws Exception { - //#coordinated-example - ActorSystem system = ActorSystem.create("CoordinatedExample"); + @Test + public void coordinatedExample() throws Exception { + //#coordinated-example + ActorSystem system = ActorSystem.create("CoordinatedExample"); - ActorRef counter1 = system.actorOf(Props.create(CoordinatedCounter.class)); - ActorRef counter2 = system.actorOf(Props.create(CoordinatedCounter.class)); + ActorRef counter1 = system.actorOf(Props.create(CoordinatedCounter.class)); + ActorRef counter2 = system.actorOf(Props.create(CoordinatedCounter.class)); - Timeout timeout = new Timeout(5, SECONDS); + Timeout timeout = new Timeout(5, SECONDS); - counter1.tell(new Coordinated(new Increment(counter2), timeout), null); + counter1.tell(new Coordinated(new Increment(counter2), timeout), null); - Integer count = (Integer) Await.result( - ask(counter1, "GetCount", timeout), timeout.duration()); - //#coordinated-example + Integer count = (Integer) Await.result( + ask(counter1, "GetCount", timeout), timeout.duration()); + //#coordinated-example - assertEquals(count, new Integer(1)); + assertEquals(count, new Integer(1)); - system.shutdown(); - } + JavaTestKit.shutdownActorSystem(system); + } - @Test - public void coordinatedApi() { - //#create-coordinated - Timeout timeout = new Timeout(5, SECONDS); - Coordinated coordinated = new Coordinated(timeout); - //#create-coordinated + @Test + public void coordinatedApi() { + //#create-coordinated + Timeout timeout = new Timeout(5, SECONDS); + Coordinated coordinated = new Coordinated(timeout); + //#create-coordinated - ActorSystem system = ActorSystem.create("CoordinatedApi"); - ActorRef actor = system.actorOf(Props.create(Coordinator.class)); + ActorSystem system = ActorSystem.create("CoordinatedApi"); + ActorRef actor = system.actorOf(Props.create(Coordinator.class)); - //#send-coordinated - actor.tell(new Coordinated(new Message(), timeout), null); - //#send-coordinated + //#send-coordinated + actor.tell(new Coordinated(new Message(), timeout), null); + //#send-coordinated - //#include-coordinated - actor.tell(coordinated.coordinate(new Message()), null); - //#include-coordinated + //#include-coordinated + actor.tell(coordinated.coordinate(new Message()), null); + //#include-coordinated - coordinated.await(); + coordinated.await(); - system.shutdown(); - } + JavaTestKit.shutdownActorSystem(system); + } - @Test - public void counterTransactor() throws Exception { - ActorSystem system = ActorSystem.create("CounterTransactor"); - ActorRef counter = system.actorOf(Props.create(Counter.class)); + @Test + public void counterTransactor() throws Exception { + ActorSystem system = ActorSystem.create("CounterTransactor"); + ActorRef counter = system.actorOf(Props.create(Counter.class)); - Timeout timeout = new Timeout(5, SECONDS); - Coordinated coordinated = new Coordinated(timeout); - counter.tell(coordinated.coordinate(new Increment()), null); - coordinated.await(); + Timeout timeout = new Timeout(5, SECONDS); + Coordinated coordinated = new Coordinated(timeout); + counter.tell(coordinated.coordinate(new Increment()), null); + coordinated.await(); - Integer count = (Integer) Await.result(ask(counter, "GetCount", timeout), timeout.duration()); - assertEquals(count, new Integer(1)); + Integer count = (Integer) Await.result(ask(counter, "GetCount", timeout), timeout.duration()); + assertEquals(count, new Integer(1)); - system.shutdown(); - } + JavaTestKit.shutdownActorSystem(system); + } - @Test - public void friendlyCounterTransactor() throws Exception { - ActorSystem system = ActorSystem.create("FriendlyCounterTransactor"); - ActorRef friend = system.actorOf(Props.create(Counter.class)); - ActorRef friendlyCounter = system.actorOf(Props.create(FriendlyCounter.class)); + @Test + public void friendlyCounterTransactor() throws Exception { + ActorSystem system = ActorSystem.create("FriendlyCounterTransactor"); + ActorRef friend = system.actorOf(Props.create(Counter.class)); + ActorRef friendlyCounter = system.actorOf(Props.create(FriendlyCounter.class)); - Timeout timeout = new Timeout(5, SECONDS); - Coordinated coordinated = new Coordinated(timeout); - friendlyCounter.tell(coordinated.coordinate(new Increment(friend)), null); - coordinated.await(); + Timeout timeout = new Timeout(5, SECONDS); + Coordinated coordinated = new Coordinated(timeout); + friendlyCounter.tell(coordinated.coordinate(new Increment(friend)), null); + coordinated.await(); - Integer count1 = (Integer) Await.result(ask(friendlyCounter, "GetCount", timeout), timeout.duration()); - assertEquals(count1, new Integer(1)); + Integer count1 = (Integer) Await.result(ask(friendlyCounter, "GetCount", timeout), timeout.duration()); + assertEquals(count1, new Integer(1)); - Integer count2 = (Integer) Await.result(ask(friend, "GetCount", timeout), timeout.duration()); - assertEquals(count2, new Integer(1)); + Integer count2 = (Integer) Await.result(ask(friend, "GetCount", timeout), timeout.duration()); + assertEquals(count2, new Integer(1)); - system.shutdown(); - } + JavaTestKit.shutdownActorSystem(system); + } } diff --git a/akka-docs/rst/java/code/docs/zeromq/ZeromqDocTestBase.java b/akka-docs/rst/java/code/docs/zeromq/ZeromqDocTestBase.java index 51afb9d119..a316f92822 100644 --- a/akka-docs/rst/java/code/docs/zeromq/ZeromqDocTestBase.java +++ b/akka-docs/rst/java/code/docs/zeromq/ZeromqDocTestBase.java @@ -30,6 +30,7 @@ import akka.actor.UntypedActor; import akka.actor.Props; import akka.event.Logging; import akka.event.LoggingAdapter; +import org.junit.*; import scala.concurrent.duration.Duration; import akka.serialization.SerializationExtension; import akka.serialization.Serialization; @@ -47,26 +48,16 @@ import java.text.SimpleDateFormat; import akka.actor.ActorSystem; import akka.testkit.AkkaSpec; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.Assume; +import akka.testkit.AkkaJUnitActorSystemResource; public class ZeromqDocTestBase { - ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("ZeromqDocTest", + ConfigFactory.parseString("akka.loglevel=INFO").withFallback(AkkaSpec.testConf())); - @Before - public void setUp() { - system = ActorSystem.create("ZeromqDocTest", - ConfigFactory.parseString("akka.loglevel=INFO").withFallback(AkkaSpec.testConf())); - } - - @After - public void tearDown() { - system.shutdown(); - } + private final ActorSystem system = actorSystemResource.getSystem(); @SuppressWarnings("unused") @Test diff --git a/akka-docs/rst/scala/code/docs/actor/ActorDocSpec.scala b/akka-docs/rst/scala/code/docs/actor/ActorDocSpec.scala index 60125052ea..0df50cb494 100644 --- a/akka-docs/rst/scala/code/docs/actor/ActorDocSpec.scala +++ b/akka-docs/rst/scala/code/docs/actor/ActorDocSpec.scala @@ -267,7 +267,7 @@ class ActorDocSpec extends AkkaSpec(Map("akka.loglevel" -> "INFO")) { val system = ActorSystem("mySystem") val myActor = system.actorOf(Props[MyActor].withDispatcher("my-dispatcher"), "myactor2") //#system-actorOf - system.shutdown() + shutdown(system) } "creating actor with IndirectActorProducer" in { diff --git a/akka-docs/rst/scala/code/docs/remoting/RemoteDeploymentDocSpec.scala b/akka-docs/rst/scala/code/docs/remoting/RemoteDeploymentDocSpec.scala index 737fde572d..3cd3efb73f 100644 --- a/akka-docs/rst/scala/code/docs/remoting/RemoteDeploymentDocSpec.scala +++ b/akka-docs/rst/scala/code/docs/remoting/RemoteDeploymentDocSpec.scala @@ -28,7 +28,7 @@ class RemoteDeploymentDocSpec extends AkkaSpec(""" val other = ActorSystem("remote", system.settings.config) val address = other.asInstanceOf[ExtendedActorSystem].provider.getExternalAddressFor(Address("akka.tcp", "s", "host", 1)).get - override def afterTermination() { other.shutdown() } + override def afterTermination() { shutdown(other) } "demonstrate programmatic deployment" in { //#deploy diff --git a/akka-docs/rst/scala/code/docs/serialization/SerializationDocSpec.scala b/akka-docs/rst/scala/code/docs/serialization/SerializationDocSpec.scala index 99fdf48bea..74ae1cf4d0 100644 --- a/akka-docs/rst/scala/code/docs/serialization/SerializationDocSpec.scala +++ b/akka-docs/rst/scala/code/docs/serialization/SerializationDocSpec.scala @@ -64,7 +64,7 @@ package docs.serialization { //#serialize-messages-config val a = ActorSystem("system", config) a.settings.SerializeAllMessages must be(true) - a.shutdown() + shutdown(a) } "demonstrate configuration of serialize creators" in { @@ -79,7 +79,7 @@ package docs.serialization { //#serialize-creators-config val a = ActorSystem("system", config) a.settings.SerializeAllCreators must be(true) - a.shutdown() + shutdown(a) } "demonstrate configuration of serializers" in { @@ -97,7 +97,7 @@ package docs.serialization { """) //#serialize-serializers-config val a = ActorSystem("system", config) - a.shutdown() + shutdown(a) } "demonstrate configuration of serialization-bindings" in { @@ -126,7 +126,7 @@ package docs.serialization { SerializationExtension(a).serializerFor(classOf[String]).getClass must equal(classOf[JavaSerializer]) SerializationExtension(a).serializerFor(classOf[Customer]).getClass must equal(classOf[JavaSerializer]) SerializationExtension(a).serializerFor(classOf[java.lang.Boolean]).getClass must equal(classOf[MyOwnSerializer]) - a.shutdown() + shutdown(a) } "demonstrate the programmatic API" in { @@ -152,7 +152,7 @@ package docs.serialization { back must equal(original) //#programmatic - system.shutdown() + shutdown(system) } "demonstrate serialization of ActorRefs" in { diff --git a/akka-docs/rst/scala/code/docs/testkit/PlainWordSpec.scala b/akka-docs/rst/scala/code/docs/testkit/PlainWordSpec.scala index 44d13f640f..1ec36b12c5 100644 --- a/akka-docs/rst/scala/code/docs/testkit/PlainWordSpec.scala +++ b/akka-docs/rst/scala/code/docs/testkit/PlainWordSpec.scala @@ -31,7 +31,7 @@ class MySpec(_system: ActorSystem) extends TestKit(_system) with ImplicitSender import MySpec._ override def afterAll { - system.shutdown() + TestKit.shutdownActorSystem(system) } "An Echo actor" must { diff --git a/akka-docs/rst/scala/code/docs/testkit/TestKitUsageSpec.scala b/akka-docs/rst/scala/code/docs/testkit/TestKitUsageSpec.scala index d8f9e1c14e..3775b49636 100644 --- a/akka-docs/rst/scala/code/docs/testkit/TestKitUsageSpec.scala +++ b/akka-docs/rst/scala/code/docs/testkit/TestKitUsageSpec.scala @@ -45,7 +45,7 @@ class TestKitUsageSpec system.actorOf(Props(classOf[SequencingActor], testActor, headList, tailList)) override def afterAll { - system.shutdown() + shutdown(system) } "An EchoActor" should { diff --git a/akka-docs/rst/scala/code/docs/testkit/TestkitDocSpec.scala b/akka-docs/rst/scala/code/docs/testkit/TestkitDocSpec.scala index 3696e9e434..4a32ec463c 100644 --- a/akka-docs/rst/scala/code/docs/testkit/TestkitDocSpec.scala +++ b/akka-docs/rst/scala/code/docs/testkit/TestkitDocSpec.scala @@ -264,7 +264,7 @@ class TestkitDocSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { actor ! Kill } } finally { - system.shutdown() + shutdown(system) } //#event-filter } @@ -282,7 +282,7 @@ class TestkitDocSpec extends AkkaSpec with DefaultTimeout with ImplicitSender { try expectMsg("hello") catch { case NonFatal(e) ⇒ system.shutdown(); throw e } //#put-your-test-code-here - system.shutdown() + shutdown(system) } //#test-kit-base } diff --git a/akka-docs/rst/scala/code/docs/transactor/TransactorDocSpec.scala b/akka-docs/rst/scala/code/docs/transactor/TransactorDocSpec.scala index 6807dd4645..2c9a726d7e 100644 --- a/akka-docs/rst/scala/code/docs/transactor/TransactorDocSpec.scala +++ b/akka-docs/rst/scala/code/docs/transactor/TransactorDocSpec.scala @@ -161,7 +161,7 @@ class TransactorDocSpec extends AkkaSpec { count must be === 1 - system.shutdown() + shutdown(system) } "coordinated api" in { @@ -191,7 +191,7 @@ class TransactorDocSpec extends AkkaSpec { coordinated.await() - system.shutdown() + shutdown(system) } "counter transactor" in { @@ -208,7 +208,7 @@ class TransactorDocSpec extends AkkaSpec { underlyingCounter.count.single.get must be === 1 - system.shutdown() + shutdown(system) } "friendly counter transactor" in { @@ -229,6 +229,6 @@ class TransactorDocSpec extends AkkaSpec { underlyingFriendlyCounter.count.single.get must be === 1 underlyingFriend.count.single.get must be === 1 - system.shutdown() + shutdown(system) } } diff --git a/akka-durable-mailboxes/akka-mailboxes-common/src/test/scala/akka/actor/mailbox/DurableMailboxSpec.scala b/akka-durable-mailboxes/akka-mailboxes-common/src/test/scala/akka/actor/mailbox/DurableMailboxSpec.scala index 804043711f..37ba1df081 100644 --- a/akka-durable-mailboxes/akka-mailboxes-common/src/test/scala/akka/actor/mailbox/DurableMailboxSpec.scala +++ b/akka-durable-mailboxes/akka-mailboxes-common/src/test/scala/akka/actor/mailbox/DurableMailboxSpec.scala @@ -80,7 +80,7 @@ abstract class DurableMailboxSpec(system: ActorSystem, val backendName: String) protected def atStartup() {} final override def afterAll { - system.shutdown() + TestKit.shutdownActorSystem(system) try system.awaitTermination(5 seconds) catch { case _: TimeoutException ⇒ system.log.warning("Failed to stop [{}] within 5 seconds", system.name) } diff --git a/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/MultiNodeSpec.scala b/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/MultiNodeSpec.scala index c75e052993..32f262329a 100644 --- a/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/MultiNodeSpec.scala +++ b/akka-multi-node-testkit/src/main/scala/akka/remote/testkit/MultiNodeSpec.scala @@ -268,14 +268,7 @@ abstract class MultiNodeSpec(val myself: RoleName, _system: ActorSystem, _roles: } } } - system.shutdown() - try system.awaitTermination(shutdownTimeout) catch { - case _: TimeoutException ⇒ - val msg = "Failed to stop [%s] within [%s] \n%s".format(system.name, shutdownTimeout, - system.asInstanceOf[ActorSystemImpl].printTree) - if (verifySystemShutdown) throw new RuntimeException(msg) - else system.log.warning(msg) - } + shutdown(system) afterTermination() } diff --git a/akka-remote/src/test/scala/akka/remote/RemoteDeathWatchSpec.scala b/akka-remote/src/test/scala/akka/remote/RemoteDeathWatchSpec.scala index 07fe7bdba4..09b5fbd60c 100644 --- a/akka-remote/src/test/scala/akka/remote/RemoteDeathWatchSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemoteDeathWatchSpec.scala @@ -34,7 +34,7 @@ akka { } override def afterTermination() { - other.shutdown() + shutdown(other) } "receive Terminated when watched node is unknown host" in { diff --git a/akka-remote/src/test/scala/akka/remote/RemoteRouterSpec.scala b/akka-remote/src/test/scala/akka/remote/RemoteRouterSpec.scala index a993511b21..56aab5e4cd 100644 --- a/akka-remote/src/test/scala/akka/remote/RemoteRouterSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemoteRouterSpec.scala @@ -71,7 +71,7 @@ akka.actor.deployment { val otherSystem = ActorSystem("remote-sys", conf) override def afterTermination() { - otherSystem.shutdown() + shutdown(otherSystem) } "A Remote Router" must { diff --git a/akka-remote/src/test/scala/akka/remote/RemoteWatcherSpec.scala b/akka-remote/src/test/scala/akka/remote/RemoteWatcherSpec.scala index 56c7c69508..b7a9519543 100644 --- a/akka-remote/src/test/scala/akka/remote/RemoteWatcherSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemoteWatcherSpec.scala @@ -96,7 +96,7 @@ class RemoteWatcherSpec extends AkkaSpec( akka.remote.transport.ActorTransportAdapter.DisassociateUnderlying.getClass)(_)) override def afterTermination() { - remoteSystem.shutdown() + shutdown(remoteSystem) } val heartbeatMsgB = Heartbeat(remoteAddressUid) diff --git a/akka-remote/src/test/scala/akka/remote/RemotingSpec.scala b/akka-remote/src/test/scala/akka/remote/RemotingSpec.scala index 29255c7785..e7e3f1ebc4 100644 --- a/akka-remote/src/test/scala/akka/remote/RemotingSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/RemotingSpec.scala @@ -201,7 +201,7 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D val maxPayloadBytes = system.settings.config.getBytes("akka.remote.test.maximum-payload-bytes").toInt override def afterTermination() { - remoteSystem.shutdown() + shutdown(remoteSystem) AssociationRegistry.clear() } @@ -258,8 +258,7 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D // then we shutdown all but one system to simulate broken connections moreSystems foreach { sys ⇒ - sys.shutdown() - sys.awaitTermination(5.seconds.dilated) + shutdown(sys) } 1 to n foreach { x ⇒ @@ -531,8 +530,7 @@ class RemotingSpec extends AkkaSpec(RemotingSpec.cfg) with ImplicitSender with D expectMsg(3.seconds, ("pong", otherGuyRemoteTest)) }(otherSystem) } finally { - otherSystem.shutdown() - otherSystem.awaitTermination(5.seconds.dilated) + shutdown(otherSystem) } } } diff --git a/akka-remote/src/test/scala/akka/remote/Ticket1978CommunicationSpec.scala b/akka-remote/src/test/scala/akka/remote/Ticket1978CommunicationSpec.scala index 6d70f2bcd5..0f216150e0 100644 --- a/akka-remote/src/test/scala/akka/remote/Ticket1978CommunicationSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/Ticket1978CommunicationSpec.scala @@ -129,8 +129,7 @@ abstract class Ticket1978CommunicationSpec(val cipherConfig: CipherConfig) exten override def afterTermination() { if (cipherConfig.runTest) { - other.shutdown() - other.awaitTermination() + shutdown(other) } } diff --git a/akka-remote/src/test/scala/akka/remote/UntrustedSpec.scala b/akka-remote/src/test/scala/akka/remote/UntrustedSpec.scala index 9124aad9c5..bbd347a1eb 100644 --- a/akka-remote/src/test/scala/akka/remote/UntrustedSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/UntrustedSpec.scala @@ -38,7 +38,7 @@ akka.loglevel = DEBUG val target2 = other.actorFor(RootActorPath(addr) / testActor.path.elements) override def afterTermination() { - other.shutdown() + shutdown(other) } // need to enable debug log-level without actually printing those messages diff --git a/akka-remote/src/test/scala/akka/remote/transport/AkkaProtocolStressTest.scala b/akka-remote/src/test/scala/akka/remote/transport/AkkaProtocolStressTest.scala index aef60384a8..960d176057 100644 --- a/akka-remote/src/test/scala/akka/remote/transport/AkkaProtocolStressTest.scala +++ b/akka-remote/src/test/scala/akka/remote/transport/AkkaProtocolStressTest.scala @@ -103,6 +103,6 @@ class AkkaProtocolStressTest extends AkkaSpec(configA) with ImplicitSender with EventFilter.warning(pattern = "received dead letter.*(InboundPayload|Disassociate)"))) } - override def afterTermination(): Unit = systemB.shutdown() + override def afterTermination(): Unit = shutdown(systemB) } diff --git a/akka-remote/src/test/scala/akka/remote/transport/SystemMessageDeliveryStressTest.scala b/akka-remote/src/test/scala/akka/remote/transport/SystemMessageDeliveryStressTest.scala index 21a80d67b7..4206702230 100644 --- a/akka-remote/src/test/scala/akka/remote/transport/SystemMessageDeliveryStressTest.scala +++ b/akka-remote/src/test/scala/akka/remote/transport/SystemMessageDeliveryStressTest.scala @@ -136,7 +136,7 @@ abstract class SystemMessageDeliveryStressTest(msg: String, cfg: String) EventFilter.warning(pattern = "received dead letter.*(InboundPayload|Disassociate)"))) } - override def afterTermination(): Unit = systemB.shutdown() + override def afterTermination(): Unit = shutdown(systemB) } diff --git a/akka-remote/src/test/scala/akka/remote/transport/ThrottlerTransportAdapterSpec.scala b/akka-remote/src/test/scala/akka/remote/transport/ThrottlerTransportAdapterSpec.scala index 13354c951f..600000cd8a 100644 --- a/akka-remote/src/test/scala/akka/remote/transport/ThrottlerTransportAdapterSpec.scala +++ b/akka-remote/src/test/scala/akka/remote/transport/ThrottlerTransportAdapterSpec.scala @@ -136,7 +136,7 @@ class ThrottlerTransportAdapterSpec extends AkkaSpec(configA) with ImplicitSende EventFilter.warning(pattern = "received dead letter.*(InboundPayload|Disassociate)"))) } - override def afterTermination(): Unit = systemB.shutdown() + override def afterTermination(): Unit = shutdown(systemB) } class ThrottlerTransportAdapterGenericSpec extends GenericTransportSpec(withAkkaProtocol = true) { diff --git a/akka-testkit/src/main/java/akka/testkit/JavaTestKit.java b/akka-testkit/src/main/java/akka/testkit/JavaTestKit.java index 8d63c89f67..372b4459f5 100644 --- a/akka-testkit/src/main/java/akka/testkit/JavaTestKit.java +++ b/akka-testkit/src/main/java/akka/testkit/JavaTestKit.java @@ -4,7 +4,6 @@ package akka.testkit; import akka.actor.Terminated; -import akka.japi.Option; import scala.runtime.AbstractFunction0; import akka.actor.ActorRef; import akka.actor.ActorSystem; @@ -15,6 +14,8 @@ import akka.japi.Util; import scala.concurrent.duration.Duration; import scala.concurrent.duration.FiniteDuration; +import java.util.concurrent.TimeUnit; + /** * Java API: Test kit for testing actors. Inheriting from this class enables * reception of replies from actors, which are queued by an internal actor and @@ -42,6 +43,29 @@ import scala.concurrent.duration.FiniteDuration; * */ public class JavaTestKit { + /** + * Shut down an actor system and wait for termination. + * On failure debug output will be logged about the remaining actors in the system. + *

+ * + * If verifySystemShutdown is true, then an exception will be thrown on failure. + */ + public static void shutdownActorSystem(ActorSystem actorSystem, Duration duration, Boolean verifySystemShutdown) { + boolean vss = verifySystemShutdown != null ? verifySystemShutdown : false; + Duration dur = duration != null ? duration : FiniteDuration.create(10, TimeUnit.SECONDS); + TestKit.shutdownActorSystem(actorSystem, dur, vss); + } + + public static void shutdownActorSystem(ActorSystem actorSystem) { + shutdownActorSystem(actorSystem, null, null); + } + public void shutdownActorSystem(ActorSystem actorSystem, Duration duration) { + shutdownActorSystem(actorSystem, duration, null); + } + public void shutdownActorSystem(ActorSystem actorSystem, Boolean verifySystemShutdown) { + shutdownActorSystem(actorSystem, null, verifySystemShutdown); + } + private final TestProbe p; public JavaTestKit(ActorSystem system) { @@ -637,4 +661,28 @@ public class JavaTestKit { } } + /** + * Shut down an actor system and wait for termination. + * On failure debug output will be logged about the remaining actors in the system. + *

+ * + * If verifySystemShutdown is true, then an exception will be thrown on failure. + */ + public void shutdown(ActorSystem actorSystem, Duration duration, Boolean verifySystemShutdown) { + boolean vss = verifySystemShutdown != null ? verifySystemShutdown : false; + Duration dur = duration != null ? duration : + TestKit.dilated(FiniteDuration.create(5, TimeUnit.SECONDS), + getSystem()).min(FiniteDuration.create(10, TimeUnit.SECONDS)); + JavaTestKit.shutdownActorSystem(actorSystem, dur, vss); + } + + public void shutdown(ActorSystem actorSystem) { + shutdown(actorSystem, null, null); + } + public void shutdown(ActorSystem actorSystem, Duration duration) { + shutdown(actorSystem, duration, null); + } + public void shutdown(ActorSystem actorSystem, Boolean verifySystemShutdown) { + shutdown(actorSystem, null, verifySystemShutdown); + } } diff --git a/akka-testkit/src/main/scala/akka/testkit/TestKit.scala b/akka-testkit/src/main/scala/akka/testkit/TestKit.scala index 123e55470d..e81b01f9bf 100644 --- a/akka-testkit/src/main/scala/akka/testkit/TestKit.scala +++ b/akka-testkit/src/main/scala/akka/testkit/TestKit.scala @@ -8,12 +8,17 @@ import scala.annotation.{ varargs, tailrec } import scala.collection.immutable import scala.concurrent.duration._ import scala.reflect.ClassTag -import java.util.concurrent.{ BlockingDeque, LinkedBlockingDeque, TimeUnit, atomic } +import java.util.concurrent._ import java.util.concurrent.atomic.AtomicInteger import akka.actor._ import akka.actor.Actor._ import akka.util.{ Timeout, BoxedType } import scala.util.control.NonFatal +import scala.Some +import java.util.concurrent.TimeUnit +import akka.actor.IllegalActorStateException +import akka.actor.DeadLetter +import akka.actor.Terminated object TestActor { type Ignore = Option[PartialFunction[Any, Boolean]] @@ -645,6 +650,18 @@ trait TestKitBase { } } + /** + * Shut down an actor system and wait for termination. + * On failure debug output will be logged about the remaining actors in the system. + * + * If verifySystemShutdown is true, then an exception will be thrown on failure. + */ + def shutdown(actorSystem: ActorSystem, + duration: Duration = 5.seconds.dilated.min(10.seconds), + verifySystemShutdown: Boolean = false) { + TestKit.shutdownActorSystem(actorSystem, duration, verifySystemShutdown) + } + private def format(u: TimeUnit, d: Duration) = "%.3f %s".format(d.toUnit(u), u.toString.toLowerCase) } @@ -727,6 +744,25 @@ object TestKit { */ def dilated(duration: Duration, system: ActorSystem): Duration = duration * TestKitExtension(system).TestTimeFactor + + /** + * Shut down an actor system and wait for termination. + * On failure debug output will be logged about the remaining actors in the system. + * + * If verifySystemShutdown is true, then an exception will be thrown on failure. + */ + def shutdownActorSystem(actorSystem: ActorSystem, + duration: Duration = 10 seconds, + verifySystemShutdown: Boolean = false): Unit = { + actorSystem.shutdown() + try actorSystem.awaitTermination(duration) catch { + case _: TimeoutException ⇒ + val msg = "Failed to stop [%s] within [%s] \n%s".format(actorSystem.name, duration, + actorSystem.asInstanceOf[ActorSystemImpl].printTree) + if (verifySystemShutdown) throw new RuntimeException(msg) + else actorSystem.log.warning(msg) + } + } } /** diff --git a/akka-testkit/src/test/java/akka/testkit/AkkaJUnitActorSystemResource.java b/akka-testkit/src/test/java/akka/testkit/AkkaJUnitActorSystemResource.java new file mode 100644 index 0000000000..83335cc98d --- /dev/null +++ b/akka-testkit/src/test/java/akka/testkit/AkkaJUnitActorSystemResource.java @@ -0,0 +1,72 @@ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package akka.testkit; + +import akka.actor.ActorSystem; +import com.typesafe.config.Config; +import org.junit.rules.ExternalResource; + +/** + * This is a resource for creating an actor system before test start and shut it down afterwards. + * + * To use it on a class level add this to your test class: + * + * @ClassRule + * public static AkkaJUnitActorSystemResource actorSystemResource = + * new AkkaJUnitActorSystemResource(name, config); + * + * private final ActorSystem system = actorSystemResource.getSystem(); + * + * + * To use it on a per test level add this to your test class: + * + * @Rule + * public AkkaJUnitActorSystemResource actorSystemResource = + * new AkkaJUnitActorSystemResource(name, config); + * + * private final ActorSystem system = actorSystemResource.getSystem(); + */ + +public class AkkaJUnitActorSystemResource extends ExternalResource { + private ActorSystem system = null; + private final String name; + private final Config config; + + private ActorSystem createSystem(String name, Config config) { + if (config == null) + return ActorSystem.create(name); + else + return ActorSystem.create(name, config); + } + + public AkkaJUnitActorSystemResource(String name, Config config) { + this.name = name; + this.config = config; + system = createSystem(name, config); + } + + public AkkaJUnitActorSystemResource(String name) { + this(name, AkkaSpec.testConf()); + } + + @Override + protected void before() throws Throwable { + // Sometimes the ExternalResource seems to be reused, and + // we don't run the constructor again, so if that's the case + // then create the system here + if (system == null) { + system = createSystem(name, config); + } + } + + @Override + protected void after() { + JavaTestKit.shutdownActorSystem(system); + system = null; + } + + public ActorSystem getSystem() { + return system; + } +} diff --git a/akka-testkit/src/test/scala/akka/testkit/AkkaSpec.scala b/akka-testkit/src/test/scala/akka/testkit/AkkaSpec.scala index be193fe17c..c234041a7c 100644 --- a/akka-testkit/src/test/scala/akka/testkit/AkkaSpec.scala +++ b/akka-testkit/src/test/scala/akka/testkit/AkkaSpec.scala @@ -73,12 +73,7 @@ abstract class AkkaSpec(_system: ActorSystem) final override def afterAll { beforeTermination() - system.shutdown() - try system.awaitTermination(5 seconds) catch { - case _: TimeoutException ⇒ - system.log.warning("Failed to stop [{}] within 5 seconds", system.name) - println(system.asInstanceOf[ActorSystemImpl].printTree) - } + shutdown(system) afterTermination() stopCoroner() } diff --git a/akka-testkit/src/test/scala/akka/testkit/AkkaSpecSpec.scala b/akka-testkit/src/test/scala/akka/testkit/AkkaSpecSpec.scala index 19ba1fa44c..aa9ad21181 100644 --- a/akka-testkit/src/test/scala/akka/testkit/AkkaSpecSpec.scala +++ b/akka-testkit/src/test/scala/akka/testkit/AkkaSpecSpec.scala @@ -28,7 +28,7 @@ class AkkaSpecSpec extends WordSpec with MustMatchers { a ! 42 } } finally { - system.shutdown() + TestKit.shutdownActorSystem(system) } } @@ -43,7 +43,7 @@ class AkkaSpecSpec extends WordSpec with MustMatchers { val ref = Seq(testActor, system.actorOf(Props.empty, "name")) } spec.ref foreach (_.isTerminated must not be true) - system.shutdown() + TestKit.shutdownActorSystem(system) spec.awaitCond(spec.ref forall (_.isTerminated), 2 seconds) } @@ -86,15 +86,15 @@ class AkkaSpecSpec extends WordSpec with MustMatchers { val latch = new TestLatch(1)(system) system.registerOnTermination(latch.countDown()) - system.shutdown() + TestKit.shutdownActorSystem(system) Await.ready(latch, 2 seconds) Await.result(davyJones ? "Die!", timeout.duration) must be === "finally gone" // this will typically also contain log messages which were sent after the logger shutdown locker must contain(DeadLetter(42, davyJones, probe.ref)) } finally { - system.shutdown() - otherSystem.shutdown() + TestKit.shutdownActorSystem(system) + TestKit.shutdownActorSystem(otherSystem) } } } diff --git a/akka-transactor/src/test/java/akka/transactor/UntypedCoordinatedIncrementTest.java b/akka-transactor/src/test/java/akka/transactor/UntypedCoordinatedIncrementTest.java index 51b87d619d..1727b7d219 100644 --- a/akka-transactor/src/test/java/akka/transactor/UntypedCoordinatedIncrementTest.java +++ b/akka-transactor/src/test/java/akka/transactor/UntypedCoordinatedIncrementTest.java @@ -6,10 +6,8 @@ package akka.transactor; import static org.junit.Assert.*; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.Before; +import akka.testkit.*; +import org.junit.*; import akka.actor.ActorSystem; import akka.actor.ActorRef; @@ -17,10 +15,7 @@ import akka.actor.Props; import scala.concurrent.Await; import scala.concurrent.Future; import static akka.pattern.Patterns.ask; -import akka.testkit.AkkaSpec; -import akka.testkit.EventFilter; -import akka.testkit.ErrorFilter; -import akka.testkit.TestEvent; + import akka.util.Timeout; import static akka.japi.Util.immutableSeq; @@ -33,18 +28,12 @@ import scala.collection.JavaConverters; import scala.collection.immutable.Seq; public class UntypedCoordinatedIncrementTest { - private static ActorSystem system; - @BeforeClass - public static void beforeAll() { - system = ActorSystem.create("UntypedCoordinatedIncrementTest", AkkaSpec.testConf()); - } + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("UntypedCoordinatedIncrementTest", AkkaSpec.testConf()); - @AfterClass - public static void afterAll() { - system.shutdown(); - system = null; - } + private final ActorSystem system = actorSystemResource.getSystem(); List counters; ActorRef failer; diff --git a/akka-transactor/src/test/java/akka/transactor/UntypedTransactorTest.java b/akka-transactor/src/test/java/akka/transactor/UntypedTransactorTest.java index 91b0d0c397..c23bfb09b5 100644 --- a/akka-transactor/src/test/java/akka/transactor/UntypedTransactorTest.java +++ b/akka-transactor/src/test/java/akka/transactor/UntypedTransactorTest.java @@ -6,10 +6,8 @@ package akka.transactor; import static org.junit.Assert.*; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.Before; +import akka.testkit.*; +import org.junit.*; import akka.actor.ActorSystem; import akka.actor.ActorRef; @@ -17,10 +15,7 @@ import akka.actor.Props; import scala.concurrent.Await; import scala.concurrent.Future; import static akka.pattern.Patterns.ask; -import akka.testkit.AkkaSpec; -import akka.testkit.EventFilter; -import akka.testkit.ErrorFilter; -import akka.testkit.TestEvent; + import akka.util.Timeout; import static akka.japi.Util.immutableSeq; @@ -34,18 +29,11 @@ import scala.collection.immutable.Seq; public class UntypedTransactorTest { - private static ActorSystem system; + @ClassRule + public static AkkaJUnitActorSystemResource actorSystemResource = + new AkkaJUnitActorSystemResource("UntypedTransactorTest", AkkaSpec.testConf()); - @BeforeClass - public static void beforeAll() { - system = ActorSystem.create("UntypedTransactorTest", AkkaSpec.testConf()); - } - - @AfterClass - public static void afterAll() { - system.shutdown(); - system = null; - } + private final ActorSystem system = actorSystemResource.getSystem(); List counters; ActorRef failer;