Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[pekko-testkit-typed] Support for JUnit5 in testkit #751

Merged
merged 13 commits into from
Nov 10, 2023
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.pekko.actor.testkit.typed.annotations;

import java.lang.annotation.*;

@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface JUnit5TestKit {}
thmue marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,9 @@ object ActorTestKit {
* The actor system has a custom guardian that allows for spawning arbitrary actors using the `spawn` methods.
*
* Designed to work with any test framework, but framework glue code that calls `shutdownTestKit` after all tests has
* run needs to be provided by the user or with [[TestKitJunitResource]].
* run needs to be provided by the user or with [[TestKitJUnitResource]].
*
* Use `TestKit.create` factories to construct manually or [[TestKitJunitResource]] to use together with JUnit tests
* Use `TestKit.create` factories to construct manually or [[TestKitJUnitResource]] to use together with JUnit tests
*
* For synchronous testing of a `Behavior` see [[BehaviorTestKit]]
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.pekko.actor.testkit.typed.javadsl

import org.apache.pekko
import com.typesafe.config.Config
import pekko.actor.testkit.typed.internal.TestKitUtils
import pekko.actor.testkit.typed.scaladsl.ActorTestKit.ApplicationTestConfig
import pekko.actor.typed.ActorSystem

final class JUnit5TestKitBuilder() {

var system: Option[ActorSystem[_]] = None

var customConfig: Config = ApplicationTestConfig

var name: String = TestKitUtils.testNameFromCallStack(classOf[JUnit5TestKitBuilder])

def withSystem(system: ActorSystem[_]): JUnit5TestKitBuilder = {
this.system = Some(system)
this
}

def withCustomConfig(customConfig: Config): JUnit5TestKitBuilder = {
this.customConfig = customConfig
this
}

def withName(name: String): JUnit5TestKitBuilder = {
this.name = name
this
}

def build(): ActorTestKit = {
if (system.isDefined) {
return ActorTestKit.create(system.get)
}
ActorTestKit.create(name, customConfig)
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* license agreements; and to You under the Apache License, version 2.0:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* This file is part of the Apache Pekko project, which was derived from Akka.
*/

package org.apache.pekko.actor.testkit.typed.javadsl

import org.junit.jupiter.api.extension.InvocationInterceptor.Invocation
import org.junit.jupiter.api.extension.{ ExtensionContext, InvocationInterceptor, ReflectiveInvocationContext }
import org.slf4j.LoggerFactory
import org.apache.pekko.actor.testkit.typed.internal.CapturingAppender

import java.lang.reflect.Method
import scala.util.control.NonFatal

final class LogCapturingExtension extends InvocationInterceptor {

private val capturingAppender = CapturingAppender.get("")

private val myLogger = LoggerFactory.getLogger(classOf[LogCapturing])

@throws[Throwable]
override def interceptTestMethod(invocation: Invocation[Void], invocationContext: ReflectiveInvocationContext[Method],
extensionContext: ExtensionContext): Unit = {

val testClassName = invocationContext.getTargetClass.getSimpleName
val testMethodName = invocationContext.getExecutable.getName

try {
myLogger.info(s"Logging started for test [${testClassName}: ${testMethodName}]")
invocation.proceed
myLogger.info(
s"Logging finished for test [${testClassName}: ${testMethodName}] that was successful")
} catch {
case NonFatal(e) =>
println(
s"--> [${Console.BLUE}${testClassName}: ${testMethodName}${Console.RESET}] " +
s"Start of log messages of test that failed with ${e.getMessage}")
capturingAppender.flush()
println(
s"<-- [${Console.BLUE}${testClassName}: ${testMethodName}${Console.RESET}] " +
s"End of log messages of test that failed with ${e.getMessage}")
throw e
} finally {

capturingAppender.clear()
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.pekko.actor.testkit.typed.javadsl

import org.apache.pekko
import pekko.actor.testkit.typed.annotations.JUnit5TestKit
import org.junit.jupiter.api.extension.{ AfterAllCallback, BeforeTestExecutionCallback, ExtensionContext }
import org.junit.platform.commons.support.AnnotationSupport

final class TestKitJUnit5Extension() extends AfterAllCallback with BeforeTestExecutionCallback {

var testKit: Option[ActorTestKit] = None

/**
* Get a reference to the field annotated with @Junit5Testkit [[Junit5TestKit]]
*/
override def beforeTestExecution(context: ExtensionContext): Unit = {

context.getTestInstance.ifPresent((instance: AnyRef) => {
val annotations = AnnotationSupport.findAnnotatedFieldValues(instance, classOf[JUnit5TestKit])
val fieldValue = annotations.stream().findFirst().orElseThrow(() =>
throw new IllegalArgumentException("Could not find field annotated with @Junit5TestKit"))
testKit = Some(fieldValue.asInstanceOf[ActorTestKit])
})
}

/**
* Shutdown testKit
*/
override def afterAll(context: ExtensionContext): Unit = {
testKit.get.shutdownTestKit()
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -59,14 +59,14 @@ import pekko.util.Timeout
* The application.conf of your project is not used in this case.
* A specific configuration can be passed as constructor parameter.
*/
final class TestKitJunitResource(_kit: ActorTestKit) extends ExternalResource {
final class TestKitJUnitResource(_kit: ActorTestKit) extends ExternalResource {

/**
* Config loaded from `application-test.conf` if that exists, otherwise
* using default configuration from the reference.conf resources that ship with the Akka libraries.
* The application.conf of your project is not used in this case.
*/
def this() = this(ActorTestKit.create(TestKitUtils.testNameFromCallStack(classOf[TestKitJunitResource])))
def this() = this(ActorTestKit.create(TestKitUtils.testNameFromCallStack(classOf[TestKitJUnitResource])))

/**
* Use a custom [[pekko.actor.typed.ActorSystem]] for the actor system.
Expand All @@ -79,20 +79,20 @@ final class TestKitJunitResource(_kit: ActorTestKit) extends ExternalResource {
def this(customConfig: String) =
this(
ActorTestKit.create(
TestKitUtils.testNameFromCallStack(classOf[TestKitJunitResource]),
TestKitUtils.testNameFromCallStack(classOf[TestKitJUnitResource]),
ConfigFactory.parseString(customConfig)))

/**
* Use a custom config for the actor system.
*/
def this(customConfig: Config) =
this(ActorTestKit.create(TestKitUtils.testNameFromCallStack(classOf[TestKitJunitResource]), customConfig))
this(ActorTestKit.create(TestKitUtils.testNameFromCallStack(classOf[TestKitJUnitResource]), customConfig))

/**
* Use a custom config for the actor system, and a custom [[pekko.actor.testkit.typed.TestKitSettings]].
*/
def this(customConfig: Config, settings: TestKitSettings) =
this(ActorTestKit.create(TestKitUtils.testNameFromCallStack(classOf[TestKitJunitResource]), customConfig, settings))
this(ActorTestKit.create(TestKitUtils.testNameFromCallStack(classOf[TestKitJUnitResource]), customConfig, settings))

@Rule
val testKit: ActorTestKit = _kit
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* license agreements; and to You under the Apache License, version 2.0:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* This file is part of the Apache Pekko project, which was derived from Akka.
*/

package jdocs.org.apache.pekko.actor.testkit.typed.javadsl;

import org.apache.pekko.actor.testkit.typed.annotations.JUnit5TestKit;
import org.apache.pekko.actor.Address;
import org.apache.pekko.actor.testkit.typed.javadsl.*;
import org.apache.pekko.actor.testkit.typed.javadsl.JUnit5TestKitBuilder;
import org.apache.pekko.actor.typed.ActorRef;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;

// #junit5-integration
@DisplayName("JUnit5")
@ExtendWith(TestKitJUnit5Extension.class)
class JUnit5IntegrationExampleTest {

@JUnit5TestKit public ActorTestKit testKit = new JUnit5TestKitBuilder().build();

@Test
void junit5Test() {
Address address = testKit.system().address();
assertNotNull(address);
}

@Test
void testSomething() {

ActorRef<AsyncTestingExampleTest.Echo.Ping> pinger =
testKit.spawn(AsyncTestingExampleTest.Echo.create(), "ping");
TestProbe<AsyncTestingExampleTest.Echo.Pong> probe = testKit.createTestProbe();
pinger.tell(new AsyncTestingExampleTest.Echo.Ping("hello", probe.ref()));
AsyncTestingExampleTest.Echo.Pong pong =
probe.expectMessage(new AsyncTestingExampleTest.Echo.Pong("hello"));
assertEquals("hello", pong.message);
}

@Test
void testSomething2() {
ActorRef<AsyncTestingExampleTest.Echo.Ping> pinger2 =
testKit.spawn(AsyncTestingExampleTest.Echo.create(), "ping2");
TestProbe<AsyncTestingExampleTest.Echo.Pong> probe2 = testKit.createTestProbe();
pinger2.tell(new AsyncTestingExampleTest.Echo.Ping("hello", probe2.ref()));
AsyncTestingExampleTest.Echo.Pong pong =
probe2.expectMessage(new AsyncTestingExampleTest.Echo.Pong("hello"));
assertEquals("hello", pong.message);
}
}
// #junit5-integration
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@
import org.junit.Rule;

// #junit-integration
import org.apache.pekko.actor.testkit.typed.javadsl.TestKitJunitResource;
import org.apache.pekko.actor.testkit.typed.javadsl.TestKitJUnitResource;
import org.apache.pekko.actor.testkit.typed.javadsl.TestProbe;
import org.apache.pekko.actor.typed.ActorRef;
import org.junit.ClassRule;
import org.junit.Test;

public class JunitIntegrationExampleTest {
public class JUnitIntegrationExampleTest {

@ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource();
@ClassRule public static final TestKitJUnitResource testKit = new TestKitJUnitResource();

// #junit-integration
// this is shown in LogCapturingExampleTest
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@

// #log-capturing
import org.apache.pekko.actor.testkit.typed.javadsl.LogCapturing;
import org.apache.pekko.actor.testkit.typed.javadsl.TestKitJunitResource;
import org.apache.pekko.actor.testkit.typed.javadsl.TestKitJUnitResource;
import org.apache.pekko.actor.testkit.typed.javadsl.TestProbe;
import org.apache.pekko.actor.typed.ActorRef;
import org.junit.ClassRule;
Expand All @@ -26,7 +26,7 @@

public class LogCapturingExampleTest {

@ClassRule public static final TestKitJunitResource testKit = new TestKitJunitResource();
@ClassRule public static final TestKitJUnitResource testKit = new TestKitJUnitResource();
thmue marked this conversation as resolved.
Show resolved Hide resolved

@Rule public final LogCapturing logCapturing = new LogCapturing();

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package jdocs.org.apache.pekko.actor.testkit.typed.javadsl;

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* license agreements; and to You under the Apache License, version 2.0:
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* This file is part of the Apache Pekko project, which was derived from Akka.
*/

// #log-capturing-junit5

import org.apache.pekko.actor.testkit.typed.annotations.JUnit5TestKit;
import org.apache.pekko.actor.testkit.typed.javadsl.*;
import org.apache.pekko.actor.testkit.typed.javadsl.JUnit5TestKitBuilder;
import org.apache.pekko.actor.typed.ActorRef;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import static jdocs.org.apache.pekko.actor.testkit.typed.javadsl.AsyncTestingExampleTest.Echo;

// test code copied from LogCapturingExampleTest.java

@DisplayName("Junit5 log capturing")
@ExtendWith(TestKitJUnit5Extension.class)
@ExtendWith(LogCapturingExtension.class)
class LogCapturingExtensionExampleTest {

@JUnit5TestKit public ActorTestKit testKit = new JUnit5TestKitBuilder().build();

@Test
void testSomething() {
ActorRef<Echo.Ping> pinger = testKit.spawn(Echo.create(), "ping");
TestProbe<Echo.Pong> probe = testKit.createTestProbe();
pinger.tell(new Echo.Ping("hello", probe.ref()));
probe.expectMessage(new Echo.Pong("hello"));
}

@Test
void testSomething2() {
ActorRef<Echo.Ping> pinger = testKit.spawn(Echo.create(), "ping");
TestProbe<Echo.Pong> probe = testKit.createTestProbe();
pinger.tell(new Echo.Ping("hello", probe.ref()));
probe.expectMessage(new Echo.Pong("hello"));
}
}
// #log-capturing-junit5
Loading