Introduce ApplicationEvents to assert events published during tests

This commit introduces a new feature in the Spring TestContext
Framework (TCF) that provides support for recording application events
published in the ApplicationContext so that assertions can be performed
against those events within tests. All events published during the
execution of a single test are made available via the ApplicationEvents
API which allows one to process the events as a java.util.Stream.

The following example demonstrates usage of this new feature.

@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents
class OrderServiceTests {

    @Autowired
    OrderService orderService;

    @Autowired
    ApplicationEvents events;

    @Test
    void submitOrder() {
        // Invoke method in OrderService that publishes an event
        orderService.submitOrder(new Order(/* ... */));
        // Verify that an OrderSubmitted event was published
        int numEvents = events.stream(OrderSubmitted.class).count();
        assertThat(numEvents).isEqualTo(1);
    }
}

To enable the feature, a test class must be annotated or meta-annotated
with @RecordApplicationEvents. Behind the scenes, a new
ApplicationEventsTestExecutionListener manages the registration of
ApplicationEvents for the current thread at various points within the
test execution lifecycle and makes the current instance of
ApplicationEvents available to tests via an @Autowired field in the
test class. The latter is made possible by a custom ObjectFactory that
is registered as a "resolvable dependency". Thanks to the magic of
ObjectFactoryDelegatingInvocationHandler in the spring-beans module,
the ApplicationEvents instance injected into test classes is
effectively a scoped-proxy that always accesses the ApplicationEvents
managed for the current test.

The current ApplicationEvents instance is stored in a ThreadLocal
variable which is made available in the ApplicationEventsHolder.
Although this class is public, it is only intended for use within the
TCF or in the implementation of third-party extensions.

ApplicationEventsApplicationListener is responsible for listening to
all application events and recording them in the current
ApplicationEvents instance. A single
ApplicationEventsApplicationListener is registered with the test's
ApplicationContext by the ApplicationEventsTestExecutionListener.

The SpringExtension has also been updated to support parameters of type
ApplicationEvents via the JUnit Jupiter ParameterResolver extension
API. This allows JUnit Jupiter based tests to receive access to the
current ApplicationEvents via test and lifecycle method parameters as
an alternative to @Autowired fields in the test class.

Closes gh-25616
This commit is contained in:
Sam Brannen
2020-08-19 22:16:34 +02:00
parent 65a395ef0e
commit 1565f4b83e
24 changed files with 1679 additions and 35 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2019 the original author or authors.
* Copyright 2002-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -24,6 +24,7 @@ import org.junit.jupiter.api.Test;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.AnnotationConfigurationException;
import org.springframework.test.context.event.ApplicationEventsTestExecutionListener;
import org.springframework.test.context.event.EventPublishingTestExecutionListener;
import org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener;
import org.springframework.test.context.support.AbstractTestExecutionListener;
@@ -56,10 +57,15 @@ class TestExecutionListenersTests {
@Test
void defaultListeners() {
List<Class<?>> expected = asList(ServletTestExecutionListener.class,
DirtiesContextBeforeModesTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class,
SqlScriptsTestExecutionListener.class, EventPublishingTestExecutionListener.class);
List<Class<?>> expected = asList(ServletTestExecutionListener.class,//
DirtiesContextBeforeModesTestExecutionListener.class,//
ApplicationEventsTestExecutionListener.class,//
DependencyInjectionTestExecutionListener.class,//
DirtiesContextTestExecutionListener.class,//
TransactionalTestExecutionListener.class,//
SqlScriptsTestExecutionListener.class,//
EventPublishingTestExecutionListener.class
);
assertRegisteredListeners(DefaultListenersTestCase.class, expected);
}
@@ -68,10 +74,16 @@ class TestExecutionListenersTests {
*/
@Test
void defaultListenersMergedWithCustomListenerPrepended() {
List<Class<?>> expected = asList(QuuxTestExecutionListener.class, ServletTestExecutionListener.class,
DirtiesContextBeforeModesTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class,
SqlScriptsTestExecutionListener.class, EventPublishingTestExecutionListener.class);
List<Class<?>> expected = asList(QuuxTestExecutionListener.class,//
ServletTestExecutionListener.class,//
DirtiesContextBeforeModesTestExecutionListener.class,//
ApplicationEventsTestExecutionListener.class,//
DependencyInjectionTestExecutionListener.class,//
DirtiesContextTestExecutionListener.class,//
TransactionalTestExecutionListener.class,//
SqlScriptsTestExecutionListener.class,//
EventPublishingTestExecutionListener.class
);
assertRegisteredListeners(MergedDefaultListenersWithCustomListenerPrependedTestCase.class, expected);
}
@@ -80,11 +92,16 @@ class TestExecutionListenersTests {
*/
@Test
void defaultListenersMergedWithCustomListenerAppended() {
List<Class<?>> expected = asList(ServletTestExecutionListener.class,
DirtiesContextBeforeModesTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class,
SqlScriptsTestExecutionListener.class, EventPublishingTestExecutionListener.class,
BazTestExecutionListener.class);
List<Class<?>> expected = asList(ServletTestExecutionListener.class,//
DirtiesContextBeforeModesTestExecutionListener.class,//
ApplicationEventsTestExecutionListener.class,//
DependencyInjectionTestExecutionListener.class,//
DirtiesContextTestExecutionListener.class,//
TransactionalTestExecutionListener.class,
SqlScriptsTestExecutionListener.class,//
EventPublishingTestExecutionListener.class,//
BazTestExecutionListener.class
);
assertRegisteredListeners(MergedDefaultListenersWithCustomListenerAppendedTestCase.class, expected);
}
@@ -93,11 +110,16 @@ class TestExecutionListenersTests {
*/
@Test
void defaultListenersMergedWithCustomListenerInserted() {
List<Class<?>> expected = asList(ServletTestExecutionListener.class,
DirtiesContextBeforeModesTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,
BarTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
TransactionalTestExecutionListener.class, SqlScriptsTestExecutionListener.class,
EventPublishingTestExecutionListener.class);
List<Class<?>> expected = asList(ServletTestExecutionListener.class,//
DirtiesContextBeforeModesTestExecutionListener.class,//
ApplicationEventsTestExecutionListener.class,//
DependencyInjectionTestExecutionListener.class,//
BarTestExecutionListener.class,//
DirtiesContextTestExecutionListener.class,//
TransactionalTestExecutionListener.class,//
SqlScriptsTestExecutionListener.class,//
EventPublishingTestExecutionListener.class
);
assertRegisteredListeners(MergedDefaultListenersWithCustomListenerInsertedTestCase.class, expected);
}

View File

@@ -0,0 +1,91 @@
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.test.context.junit.jupiter.event;
import java.util.Iterator;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.springframework.test.context.event.ApplicationEventsHolder;
/**
* Default implementation of {@link PublishedEvents}.
*
* <p>Copied from the Moduliths project.
*
* @author Oliver Drotbohm
* @author Sam Brannen
* @since 5.3.3
*/
class DefaultPublishedEvents implements PublishedEvents {
@Override
public <T> TypedPublishedEvents<T> ofType(Class<T> type) {
return SimpleTypedPublishedEvents.of(ApplicationEventsHolder.getRequiredApplicationEvents().stream(type));
}
private static class SimpleTypedPublishedEvents<T> implements TypedPublishedEvents<T> {
private final List<T> events;
private SimpleTypedPublishedEvents(List<T> events) {
this.events = events;
}
static <T> SimpleTypedPublishedEvents<T> of(Stream<T> stream) {
return new SimpleTypedPublishedEvents<>(stream.collect(Collectors.toList()));
}
@Override
public <S extends T> TypedPublishedEvents<S> ofSubType(Class<S> subType) {
return SimpleTypedPublishedEvents.of(getFilteredEvents(subType::isInstance)//
.map(subType::cast));
}
@Override
public TypedPublishedEvents<T> matching(Predicate<? super T> predicate) {
return SimpleTypedPublishedEvents.of(getFilteredEvents(predicate));
}
@Override
public <S> TypedPublishedEvents<T> matchingMapped(Function<T, S> mapper, Predicate<? super S> predicate) {
return SimpleTypedPublishedEvents.of(this.events.stream().flatMap(it -> {
S mapped = mapper.apply(it);
return predicate.test(mapped) ? Stream.of(it) : Stream.empty();
}));
}
private Stream<T> getFilteredEvents(Predicate<? super T> predicate) {
return this.events.stream().filter(predicate);
}
@Override
public Iterator<T> iterator() {
return this.events.iterator();
}
@Override
public String toString() {
return this.events.toString();
}
}
}

View File

@@ -0,0 +1,275 @@
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.test.context.junit.jupiter.event;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.event.ApplicationEvents;
import org.springframework.test.context.event.RecordApplicationEvents;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_METHOD;
/**
* Integration tests for {@link ApplicationEvents} in conjunction with JUnit Jupiter.
*
* @author Sam Brannen
* @since 5.3.3
*/
@SpringJUnitConfig
@RecordApplicationEvents
class JUnitJupiterApplicationEventsIntegrationTests {
@Autowired
ApplicationContext context;
@Autowired
ApplicationEvents applicationEvents;
@Nested
@TestInstance(PER_METHOD)
class TestInstancePerMethodTests {
@BeforeEach
void beforeEach() {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent");
context.publishEvent(new CustomEvent("beforeEach"));
assertCustomEvents(applicationEvents, "beforeEach");
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent");
}
@Test
void test1(ApplicationEvents events, TestInfo testInfo) {
assertTestExpectations(events, testInfo);
}
@Test
void test2(@Autowired ApplicationEvents events, TestInfo testInfo) {
assertTestExpectations(events, testInfo);
}
private void assertTestExpectations(ApplicationEvents events, TestInfo testInfo) {
String testName = testInfo.getTestMethod().get().getName();
assertEventTypes(events, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent",
"BeforeTestExecutionEvent");
context.publishEvent(new CustomEvent(testName));
context.publishEvent("payload1");
context.publishEvent("payload2");
assertCustomEvents(events, "beforeEach", testName);
assertPayloads(events.stream(String.class), "payload1", "payload2");
}
@AfterEach
void afterEach(@Autowired ApplicationEvents events, TestInfo testInfo) {
String testName = testInfo.getTestMethod().get().getName();
assertEventTypes(events, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent",
"BeforeTestExecutionEvent", "CustomEvent", "PayloadApplicationEvent", "PayloadApplicationEvent",
"AfterTestExecutionEvent");
context.publishEvent(new CustomEvent("afterEach"));
assertCustomEvents(events, "beforeEach", testName, "afterEach");
assertEventTypes(events, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent",
"BeforeTestExecutionEvent", "CustomEvent", "PayloadApplicationEvent", "PayloadApplicationEvent",
"AfterTestExecutionEvent", "CustomEvent");
}
}
@Nested
@TestInstance(PER_METHOD)
class TestInstancePerMethodWithClearedEventsTests {
@BeforeEach
void beforeEach() {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent");
context.publishEvent(new CustomEvent("beforeEach"));
assertCustomEvents(applicationEvents, "beforeEach");
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent");
applicationEvents.clear();
assertThat(applicationEvents.stream()).isEmpty();
}
@Test
void test1(ApplicationEvents events, TestInfo testInfo) {
assertTestExpectations(events, testInfo);
}
@Test
void test2(@Autowired ApplicationEvents events, TestInfo testInfo) {
assertTestExpectations(events, testInfo);
}
private void assertTestExpectations(ApplicationEvents events, TestInfo testInfo) {
String testName = testInfo.getTestMethod().get().getName();
assertEventTypes(events, "BeforeTestExecutionEvent");
context.publishEvent(new CustomEvent(testName));
assertCustomEvents(events, testName);
assertEventTypes(events, "BeforeTestExecutionEvent", "CustomEvent");
}
@AfterEach
void afterEach(@Autowired ApplicationEvents events, TestInfo testInfo) {
events.clear();
context.publishEvent(new CustomEvent("afterEach"));
assertCustomEvents(events, "afterEach");
assertEventTypes(events, "CustomEvent");
}
}
@Nested
@TestInstance(PER_CLASS)
class TestInstancePerClassTests {
private boolean testAlreadyExecuted = false;
@BeforeEach
void beforeEach(TestInfo testInfo) {
if (!testAlreadyExecuted) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestClassEvent",
"BeforeTestMethodEvent");
}
else {
assertEventTypes(applicationEvents, "BeforeTestMethodEvent");
}
context.publishEvent(new CustomEvent("beforeEach"));
assertCustomEvents(applicationEvents, "beforeEach");
if (!testAlreadyExecuted) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestClassEvent",
"BeforeTestMethodEvent", "CustomEvent");
}
else {
assertEventTypes(applicationEvents, "BeforeTestMethodEvent", "CustomEvent");
}
}
@Test
void test1(ApplicationEvents events, TestInfo testInfo) {
assertTestExpectations(events, testInfo);
}
@Test
void test2(@Autowired ApplicationEvents events, TestInfo testInfo) {
assertTestExpectations(events, testInfo);
}
private void assertTestExpectations(ApplicationEvents events, TestInfo testInfo) {
String testName = testInfo.getTestMethod().get().getName();
if (!testAlreadyExecuted) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestClassEvent",
"BeforeTestMethodEvent", "CustomEvent", "BeforeTestExecutionEvent");
}
else {
assertEventTypes(applicationEvents, "BeforeTestMethodEvent", "CustomEvent", "BeforeTestExecutionEvent");
}
context.publishEvent(new CustomEvent(testName));
assertCustomEvents(events, "beforeEach", testName);
if (!testAlreadyExecuted) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestClassEvent",
"BeforeTestMethodEvent", "CustomEvent", "BeforeTestExecutionEvent", "CustomEvent");
}
else {
assertEventTypes(applicationEvents, "BeforeTestMethodEvent", "CustomEvent", "BeforeTestExecutionEvent",
"CustomEvent");
}
}
@AfterEach
void afterEach(@Autowired ApplicationEvents events, TestInfo testInfo) {
String testName = testInfo.getTestMethod().get().getName();
if (!testAlreadyExecuted) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestClassEvent",
"BeforeTestMethodEvent", "CustomEvent", "BeforeTestExecutionEvent", "CustomEvent",
"AfterTestExecutionEvent");
}
else {
assertEventTypes(applicationEvents, "BeforeTestMethodEvent", "CustomEvent", "BeforeTestExecutionEvent",
"CustomEvent", "AfterTestExecutionEvent");
}
context.publishEvent(new CustomEvent("afterEach"));
assertCustomEvents(events, "beforeEach", testName, "afterEach");
if (!testAlreadyExecuted) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestClassEvent",
"BeforeTestMethodEvent", "CustomEvent", "BeforeTestExecutionEvent", "CustomEvent",
"AfterTestExecutionEvent", "CustomEvent");
testAlreadyExecuted = true;
}
else {
assertEventTypes(applicationEvents, "BeforeTestMethodEvent", "CustomEvent", "BeforeTestExecutionEvent",
"CustomEvent", "AfterTestExecutionEvent", "CustomEvent");
}
}
}
private static void assertEventTypes(ApplicationEvents applicationEvents, String... types) {
assertThat(applicationEvents.stream().map(event -> event.getClass().getSimpleName()))
.containsExactly(types);
}
private static void assertPayloads(Stream<String> events, String... values) {
assertThat(events).extracting(Object::toString).containsExactly(values);
}
private static void assertCustomEvents(ApplicationEvents events, String... messages) {
assertThat(events.stream(CustomEvent.class)).extracting(CustomEvent::getMessage).containsExactly(messages);
}
@Configuration
static class Config {
}
@SuppressWarnings("serial")
static class CustomEvent extends ApplicationEvent {
private final String message;
CustomEvent(String message) {
super(message);
this.message = message;
}
String getMessage() {
return message;
}
}
}

View File

@@ -0,0 +1,173 @@
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.test.context.junit.jupiter.event;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.TestInstance.Lifecycle;
import org.junit.jupiter.api.parallel.Execution;
import org.junit.jupiter.api.parallel.ExecutionMode;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.junit.platform.testkit.engine.EngineTestKit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.event.ApplicationEvents;
import org.springframework.test.context.event.RecordApplicationEvents;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.platform.engine.discovery.DiscoverySelectors.selectClass;
/**
* Integration tests that verify parallel execution support for {@link ApplicationEvents}
* in conjunction with JUnit Jupiter.
*
* @author Sam Brannen
* @since 5.3.3
*/
class ParallelApplicationEventsIntegrationTests {
private static final Set<String> payloads = ConcurrentHashMap.newKeySet();
@ParameterizedTest
@ValueSource(classes = {TestInstancePerMethodTestCase.class, TestInstancePerClassTestCase.class})
void executeTestsInParallel(Class<?> testClass) {
EngineTestKit.engine("junit-jupiter")//
.selectors(selectClass(testClass))//
.configurationParameter("junit.jupiter.execution.parallel.enabled", "true")//
.configurationParameter("junit.jupiter.execution.parallel.config.dynamic.factor", "10")//
.execute()//
.testEvents()//
.assertStatistics(stats -> stats.started(10).succeeded(10).failed(0));
Set<String> testNames = payloads.stream()//
.map(payload -> payload.substring(0, payload.indexOf("-")))//
.collect(Collectors.toSet());
Set<String> threadNames = payloads.stream()//
.map(payload -> payload.substring(payload.indexOf("-")))//
.collect(Collectors.toSet());
assertThat(payloads).hasSize(10);
assertThat(testNames).hasSize(10);
// There are probably 10 different thread names, but we really just want
// to assert that at least a few different threads were used.
assertThat(threadNames).hasSizeGreaterThanOrEqualTo(4);
}
@AfterEach
void resetPayloads() {
payloads.clear();
}
@SpringJUnitConfig
@RecordApplicationEvents
@Execution(ExecutionMode.CONCURRENT)
@TestInstance(Lifecycle.PER_METHOD)
static class TestInstancePerMethodTestCase {
@Autowired
ApplicationContext context;
@Autowired
ApplicationEvents events;
@Test
void test1(TestInfo testInfo) {
assertTestExpectations(this.events, testInfo);
}
@Test
void test2(ApplicationEvents events, TestInfo testInfo) {
assertTestExpectations(events, testInfo);
}
@Test
void test3(TestInfo testInfo) {
assertTestExpectations(this.events, testInfo);
}
@Test
void test4(ApplicationEvents events, TestInfo testInfo) {
assertTestExpectations(events, testInfo);
}
@Test
void test5(TestInfo testInfo) {
assertTestExpectations(this.events, testInfo);
}
@Test
void test6(ApplicationEvents events, TestInfo testInfo) {
assertTestExpectations(events, testInfo);
}
@Test
void test7(TestInfo testInfo) {
assertTestExpectations(this.events, testInfo);
}
@Test
void test8(ApplicationEvents events, TestInfo testInfo) {
assertTestExpectations(events, testInfo);
}
@Test
void test9(TestInfo testInfo) {
assertTestExpectations(this.events, testInfo);
}
@Test
void test10(ApplicationEvents events, TestInfo testInfo) {
assertTestExpectations(events, testInfo);
}
private void assertTestExpectations(ApplicationEvents events, TestInfo testInfo) {
String testName = testInfo.getTestMethod().get().getName();
String threadName = Thread.currentThread().getName();
String localPayload = testName + "-" + threadName;
context.publishEvent(localPayload);
assertPayloads(events.stream(String.class), localPayload);
}
private static void assertPayloads(Stream<String> events, String... values) {
assertThat(events.peek(payloads::add)).extracting(Object::toString).containsExactly(values);
}
@Configuration
static class Config {
}
}
@TestInstance(Lifecycle.PER_CLASS)
static class TestInstancePerClassTestCase extends TestInstancePerMethodTestCase {
}
}

View File

@@ -0,0 +1,87 @@
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.test.context.junit.jupiter.event;
import java.util.Arrays;
import java.util.function.Function;
import java.util.function.Predicate;
/**
* All Spring application events fired during the test execution.
*
* <p>Copied from the Moduliths project.
*
* @author Oliver Drotbohm
* @since 5.3.3
*/
public interface PublishedEvents {
/**
* Creates a new {@link PublishedEvents} instance for the given events.
*
* @param events must not be {@literal null}
* @return will never be {@literal null}
*/
public static PublishedEvents of(Object... events) {
return of(Arrays.asList(events));
}
/**
* Returns all application events of the given type that were fired during the test execution.
*
* @param <T> the event type
* @param type must not be {@literal null}
*/
<T> TypedPublishedEvents<T> ofType(Class<T> type);
/**
* All application events of a given type that were fired during a test execution.
*
* @param <T> the event type
*/
interface TypedPublishedEvents<T> extends Iterable<T> {
/**
* Further constrain the event type for downstream assertions.
*
* @param subType the sub type
* @return will never be {@literal null}
*/
<S extends T> TypedPublishedEvents<S> ofSubType(Class<S> subType);
/**
* Returns all {@link TypedPublishedEvents} that match the given predicate.
*
* @param predicate must not be {@literal null}
* @return will never be {@literal null}
*/
TypedPublishedEvents<T> matching(Predicate<? super T> predicate);
/**
* Returns all {@link TypedPublishedEvents} that match the given predicate
* after applying the given mapping step.
*
* @param <S> the intermediate type to apply the {@link Predicate} on
* @param mapper the mapping step to extract a part of the original event
* subject to test for the {@link Predicate}
* @param predicate the {@link Predicate} to apply on the value extracted
* @return will never be {@literal null}
*/
<S> TypedPublishedEvents<T> matchingMapped(Function<T, S> mapper, Predicate<? super S> predicate);
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.test.context.junit.jupiter.event;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolver;
/**
* @author Sam Brannen
* @since 5.3.3
*/
public class PublishedEventsExtension implements ParameterResolver {
@Override
public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
return PublishedEvents.class.isAssignableFrom(parameterContext.getParameter().getType());
}
@Override
public PublishedEvents resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
return new DefaultPublishedEvents();
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.test.context.junit.jupiter.event;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.event.ApplicationEvents;
import org.springframework.test.context.event.BeforeTestExecutionEvent;
import org.springframework.test.context.event.BeforeTestMethodEvent;
import org.springframework.test.context.event.PrepareTestInstanceEvent;
import org.springframework.test.context.event.RecordApplicationEvents;
import org.springframework.test.context.event.TestContextEvent;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for the example {@link PublishedEvents} extension to the
* {@link ApplicationEvents} feature.
*
* @author Sam Brannen
* @since 5.3.3
*/
@SpringJUnitConfig
@RecordApplicationEvents
@ExtendWith(PublishedEventsExtension.class)
class PublishedEventsIntegrationTests {
@Test
void test(PublishedEvents publishedEvents) {
assertThat(publishedEvents).isNotNull();
assertThat(publishedEvents.ofType(TestContextEvent.class)).hasSize(3);
assertThat(publishedEvents.ofType(PrepareTestInstanceEvent.class)).hasSize(1);
assertThat(publishedEvents.ofType(BeforeTestMethodEvent.class)).hasSize(1);
assertThat(publishedEvents.ofType(BeforeTestExecutionEvent.class)).hasSize(1);
assertThat(publishedEvents.ofType(TestContextEvent.class).ofSubType(BeforeTestExecutionEvent.class)).hasSize(1);
}
@Configuration
static class Config {
}
}

View File

@@ -0,0 +1,123 @@
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.test.context.junit4.event;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.event.ApplicationEvents;
import org.springframework.test.context.event.RecordApplicationEvents;
import org.springframework.test.context.junit4.SpringRunner;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link ApplicationEvents} in conjunction with JUnit 4.
*
* @author Sam Brannen
* @since 5.3.3
*/
@RunWith(SpringRunner.class)
@RecordApplicationEvents
public class JUnit4ApplicationEventsIntegrationTests {
@Rule
public final TestName testName = new TestName();
@Autowired
ApplicationContext context;
@Autowired
ApplicationEvents applicationEvents;
@Before
public void beforeEach() {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent");
context.publishEvent(new CustomEvent("beforeEach"));
assertThat(applicationEvents.stream(CustomEvent.class)).extracting(CustomEvent::getMessage)//
.containsExactly("beforeEach");
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent");
}
@Test
public void test1() {
assertTestExpectations("test1");
}
@Test
public void test2() {
assertTestExpectations("test2");
}
private void assertTestExpectations(String testName) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent",
"BeforeTestExecutionEvent");
context.publishEvent(new CustomEvent(testName));
assertThat(applicationEvents.stream(CustomEvent.class)).extracting(CustomEvent::getMessage)//
.containsExactly("beforeEach", testName);
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent",
"BeforeTestExecutionEvent", "CustomEvent");
}
@After
public void afterEach() {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent",
"BeforeTestExecutionEvent", "CustomEvent", "AfterTestExecutionEvent");
context.publishEvent(new CustomEvent("afterEach"));
assertThat(applicationEvents.stream(CustomEvent.class)).extracting(CustomEvent::getMessage)//
.containsExactly("beforeEach", this.testName.getMethodName(), "afterEach");
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent",
"BeforeTestExecutionEvent", "CustomEvent", "AfterTestExecutionEvent", "CustomEvent");
}
private static void assertEventTypes(ApplicationEvents applicationEvents, String... types) {
assertThat(applicationEvents.stream().map(event -> event.getClass().getSimpleName()))
.containsExactly(types);
}
@Configuration
static class Config {
}
@SuppressWarnings("serial")
static class CustomEvent extends ApplicationEvent {
private final String message;
CustomEvent(String message) {
super(message);
this.message = message;
}
String getMessage() {
return message;
}
}
}

View File

@@ -0,0 +1,160 @@
/*
* Copyright 2002-2020 the original author or authors.
*
* Licensed 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
*
* https://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.springframework.test.context.testng.event;
import java.lang.reflect.Method;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.context.event.ApplicationEvents;
import org.springframework.test.context.event.RecordApplicationEvents;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Integration tests for {@link ApplicationEvents} in conjunction with TestNG.
*
* @author Sam Brannen
* @since 5.3.3
*/
@RecordApplicationEvents
class TestNGApplicationEventsIntegrationTests extends AbstractTestNGSpringContextTests {
@Autowired
ApplicationContext context;
@Autowired
ApplicationEvents applicationEvents;
private boolean testAlreadyExecuted = false;
@BeforeMethod
void beforeEach() {
if (!testAlreadyExecuted) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent");
}
else {
assertEventTypes(applicationEvents, "BeforeTestMethodEvent");
}
context.publishEvent(new CustomEvent("beforeEach"));
assertThat(applicationEvents.stream(CustomEvent.class)).extracting(CustomEvent::getMessage)//
.containsExactly("beforeEach");
if (!testAlreadyExecuted) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent");
}
else {
assertEventTypes(applicationEvents, "BeforeTestMethodEvent", "CustomEvent");
}
}
@Test
void test1() {
assertTestExpectations("test1");
}
@Test
void test2() {
assertTestExpectations("test2");
}
private void assertTestExpectations(String testName) {
if (!testAlreadyExecuted) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent",
"BeforeTestExecutionEvent");
}
else {
assertEventTypes(applicationEvents, "BeforeTestMethodEvent", "CustomEvent", "BeforeTestExecutionEvent");
}
context.publishEvent(new CustomEvent(testName));
assertThat(applicationEvents.stream(CustomEvent.class)).extracting(CustomEvent::getMessage)//
.containsExactly("beforeEach", testName);
if (!testAlreadyExecuted) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent",
"BeforeTestExecutionEvent", "CustomEvent");
}
else {
assertEventTypes(applicationEvents, "BeforeTestMethodEvent", "CustomEvent", "BeforeTestExecutionEvent",
"CustomEvent");
}
}
@AfterMethod
void afterEach(Method testMethod) {
if (!testAlreadyExecuted) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent",
"BeforeTestExecutionEvent", "CustomEvent", "AfterTestExecutionEvent");
}
else {
assertEventTypes(applicationEvents, "BeforeTestMethodEvent", "CustomEvent", "BeforeTestExecutionEvent",
"CustomEvent", "AfterTestExecutionEvent");
}
context.publishEvent(new CustomEvent("afterEach"));
assertThat(applicationEvents.stream(CustomEvent.class)).extracting(CustomEvent::getMessage)//
.containsExactly("beforeEach", testMethod.getName(), "afterEach");
if (!testAlreadyExecuted) {
assertEventTypes(applicationEvents, "PrepareTestInstanceEvent", "BeforeTestMethodEvent", "CustomEvent",
"BeforeTestExecutionEvent", "CustomEvent", "AfterTestExecutionEvent", "CustomEvent");
testAlreadyExecuted = true;
}
else {
assertEventTypes(applicationEvents, "BeforeTestMethodEvent", "CustomEvent", "BeforeTestExecutionEvent",
"CustomEvent", "AfterTestExecutionEvent", "CustomEvent");
}
}
private static void assertEventTypes(ApplicationEvents applicationEvents, String... types) {
assertThat(applicationEvents.stream().map(event -> event.getClass().getSimpleName()))
.containsExactly(types);
}
@Configuration
static class Config {
}
@SuppressWarnings("serial")
static class CustomEvent extends ApplicationEvent {
private final String message;
CustomEvent(String message) {
super(message);
this.message = message;
}
String getMessage() {
return message;
}
}
}