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.
@ -48,6 +48,8 @@ package org.springframework.test.context;
* ServletTestExecutionListener}</li>
* <li>{@link org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener
* DirtiesContextBeforeModesTestExecutionListener}</li>
* <li>{@link org.springframework.test.context.event.ApplicationEventsTestExecutionListener
* ApplicationEventsTestExecutionListener}</li>
* <li>{@link org.springframework.test.context.support.DependencyInjectionTestExecutionListener
* DependencyInjectionTestExecutionListener}</li>
* <li>{@link org.springframework.test.context.support.DirtiesContextTestExecutionListener

View File

@ -67,6 +67,7 @@ public @interface TestExecutionListeners {
* {@link #value}, but it may be used instead of {@link #value}.
* @see org.springframework.test.context.web.ServletTestExecutionListener
* @see org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener
* @see org.springframework.test.context.event.ApplicationEventsTestExecutionListener
* @see org.springframework.test.context.support.DependencyInjectionTestExecutionListener
* @see org.springframework.test.context.support.DirtiesContextTestExecutionListener
* @see org.springframework.test.context.transaction.TransactionalTestExecutionListener

View File

@ -0,0 +1,82 @@
/*
* 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.event;
import java.util.stream.Stream;
import org.springframework.context.ApplicationEvent;
/**
* {@code ApplicationEvents} encapsulates all {@linkplain ApplicationEvent
* application events} that were fired during the execution of a single test method.
*
* <p>To use {@code ApplicationEvents} in your tests, do the following.
* <ul>
* <li>Ensure that your test class is annotated or meta-annotated with
* {@link RecordApplicationEvents @RecordApplicationEvents}.</li>
* <li>Ensure that the {@link ApplicationEventsTestExecutionListener} is
* registered. Note, however, that it is registered by default and only needs
* to be manually registered if you have custom configuration via
* {@link org.springframework.test.context.TestExecutionListeners @TestExecutionListeners}
* that does not include the default listeners.</li>
* <li>Annotate a field of type {@code ApplicationEvents} with
* {@link org.springframework.beans.factory.annotation.Autowired @Autowired} and
* use that instance of {@code ApplicationEvents} in your test and lifecycle methods.</li>
* <li>With JUnit Jupiter, you may optionally declare a parameter of type
* {@code ApplicationEvents} in a test or lifecycle method as an alternative to
* an {@code @Autowired} field in the test class.</li>
* </ul>
*
* @author Sam Brannen
* @author Oliver Drotbohm
* @since 5.3.3
* @see RecordApplicationEvents
* @see ApplicationEventsTestExecutionListener
* @see org.springframework.context.ApplicationEvent
*/
public interface ApplicationEvents {
/**
* Stream all application events that were fired during test execution.
* @return a stream of all application events
* @see #stream(Class)
* @see #clear()
*/
Stream<ApplicationEvent> stream();
/**
* Stream all application events or event payloads of the given type that
* were fired during test execution.
* @param <T> the event type
* @param type the type of events or payloads to stream; never {@code null}
* @return a stream of all application events or event payloads of the
* specified type
* @see #stream()
* @see #clear()
*/
<T> Stream<T> stream(Class<T> type);
/**
* Clear all application events recorded by this {@code ApplicationEvents} instance.
* <p>Subsequent calls to {@link #stream()} or {@link #stream(Class)} will
* only include events recorded since this method was invoked.
* @see #stream()
* @see #stream(Class)
*/
void clear();
}

View File

@ -0,0 +1,41 @@
/*
* 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.event;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
/**
* {@link ApplicationListener} that listens to all events and adds them to the
* current {@link ApplicationEvents} instance if registered for the current thread.
*
* @author Sam Brannen
* @author Oliver Drotbohm
* @since 5.3.3
*/
class ApplicationEventsApplicationListener implements ApplicationListener<ApplicationEvent> {
@Override
public void onApplicationEvent(ApplicationEvent event) {
DefaultApplicationEvents applicationEvents =
(DefaultApplicationEvents) ApplicationEventsHolder.getApplicationEvents();
if (applicationEvents != null) {
applicationEvents.addEvent(event);
}
}
}

View File

@ -0,0 +1,107 @@
/*
* 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.event;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
/**
* Holder class to expose the application events published during the execution
* of a test in the form of a thread-bound {@link ApplicationEvents} object.
*
* <p>{@code ApplicationEvents} are registered in this holder and managed by
* the {@link ApplicationEventsTestExecutionListener}.
*
* <p>Although this class is {@code public}, it is only intended for use within
* the <em>Spring TestContext Framework</em> or in the implementation of
* third-party extensions. Test authors should therefore allow the current
* instance of {@code ApplicationEvents} to be
* {@link org.springframework.beans.factory.annotation.Autowired @Autowired}
* into a field in the test class or injected via a parameter in test and
* lifecycle methods when using JUnit Jupiter and the {@link
* org.springframework.test.context.junit.jupiter.SpringExtension SpringExtension}.
*
* @author Sam Brannen
* @author Oliver Drotbohm
* @since 5.3.3
* @see ApplicationEvents
* @see RecordApplicationEvents
* @see ApplicationEventsTestExecutionListener
*/
public abstract class ApplicationEventsHolder {
private static final ThreadLocal<DefaultApplicationEvents> applicationEvents = new ThreadLocal<>();
private ApplicationEventsHolder() {
// no-op to prevent instantiation of this holder class
}
/**
* Get the {@link ApplicationEvents} for the current thread.
* @return the current {@code ApplicationEvents}, or {@code null} if not registered
*/
@Nullable
public static ApplicationEvents getApplicationEvents() {
return applicationEvents.get();
}
/**
* Get the {@link ApplicationEvents} for the current thread.
* @return the current {@code ApplicationEvents}
* @throws IllegalStateException if an instance of {@code ApplicationEvents}
* has not been registered for the current thread
*/
@Nullable
public static ApplicationEvents getRequiredApplicationEvents() {
ApplicationEvents events = applicationEvents.get();
Assert.state(events != null, "Failed to retrieve ApplicationEvents for the current thread. " +
"Ensure that your test class is annotated with @RecordApplicationEvents " +
"and that the ApplicationEventsTestExecutionListener is registered.");
return events;
}
/**
* Register a new {@link DefaultApplicationEvents} instance to be used for the
* current thread, if necessary.
* <p>If {@link #registerApplicationEvents()} has already been called for the
* current thread, this method does not do anything.
*/
static void registerApplicationEventsIfNecessary() {
if (getApplicationEvents() == null) {
registerApplicationEvents();
}
}
/**
* Register a new {@link DefaultApplicationEvents} instance to be used for the
* current thread.
*/
static void registerApplicationEvents() {
applicationEvents.set(new DefaultApplicationEvents());
}
/**
* Remove the registration of the {@link ApplicationEvents} for the current thread.
*/
static void unregisterApplicationEvents() {
applicationEvents.remove();
}
}

View File

@ -0,0 +1,138 @@
/*
* 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.event;
import java.io.Serializable;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.Conventions;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestContextAnnotationUtils;
import org.springframework.test.context.support.AbstractTestExecutionListener;
import org.springframework.util.Assert;
/**
* {@code TestExecutionListener} which provides support for {@link ApplicationEvents}.
*
* <p>This listener manages the registration of {@code ApplicationEvents} for the
* current thread at various points within the test execution lifecycle and makes
* the current instance of {@code ApplicationEvents} available to tests via an
* {@link org.springframework.beans.factory.annotation.Autowired @Autowired}
* field in the test class.
*
* <p>If the test class is not annotated or meta-annotated with
* {@link RecordApplicationEvents @RecordApplicationEvents}, this listener
* effectively does nothing.
*
* @author Sam Brannen
* @since 5.3.3
* @see ApplicationEvents
* @see ApplicationEventsHolder
*/
public class ApplicationEventsTestExecutionListener extends AbstractTestExecutionListener {
/**
* Attribute name for a {@link TestContext} attribute which indicates
* whether the test class for the given test context is annotated with
* {@link RecordApplicationEvents @RecordApplicationEvents}.
* <p>Permissible values include {@link Boolean#TRUE} and {@link Boolean#FALSE}.
*/
private static final String RECORD_APPLICATION_EVENTS = Conventions.getQualifiedAttributeName(
ApplicationEventsTestExecutionListener.class, "recordApplicationEvents");
private static final Object applicationEventsMonitor = new Object();
/**
* Returns {@code 1800}.
*/
@Override
public final int getOrder() {
return 1800;
}
@Override
public void prepareTestInstance(TestContext testContext) throws Exception {
if (recordApplicationEvents(testContext)) {
registerListenerAndResolvableDependencyIfNecessary(testContext.getApplicationContext());
ApplicationEventsHolder.registerApplicationEvents();
}
}
@Override
public void beforeTestMethod(TestContext testContext) throws Exception {
if (recordApplicationEvents(testContext)) {
// Register a new ApplicationEvents instance for the current thread
// in case the test instance is shared -- for example, in TestNG or
// JUnit Jupiter with @TestInstance(PER_CLASS) semantics.
ApplicationEventsHolder.registerApplicationEventsIfNecessary();
}
}
@Override
public void afterTestMethod(TestContext testContext) throws Exception {
if (recordApplicationEvents(testContext)) {
ApplicationEventsHolder.unregisterApplicationEvents();
}
}
private boolean recordApplicationEvents(TestContext testContext) {
return testContext.computeAttribute(RECORD_APPLICATION_EVENTS, name ->
TestContextAnnotationUtils.hasAnnotation(testContext.getTestClass(), RecordApplicationEvents.class));
}
private void registerListenerAndResolvableDependencyIfNecessary(ApplicationContext applicationContext) {
Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext,
"The ApplicationContext for the test must be an AbstractApplicationContext");
AbstractApplicationContext aac = (AbstractApplicationContext) applicationContext;
// Synchronize to avoid race condition in parallel test execution
synchronized(applicationEventsMonitor) {
boolean notAlreadyRegistered = aac.getApplicationListeners().stream()
.map(Object::getClass)
.noneMatch(ApplicationEventsApplicationListener.class::equals);
if (notAlreadyRegistered) {
// Register a new ApplicationEventsApplicationListener.
aac.addApplicationListener(new ApplicationEventsApplicationListener());
// Register ApplicationEvents as a resolvable dependency for @Autowired support in test classes.
ConfigurableListableBeanFactory beanFactory = aac.getBeanFactory();
beanFactory.registerResolvableDependency(ApplicationEvents.class, new ApplicationEventsObjectFactory());
}
}
}
/**
* Factory that exposes the current {@link ApplicationEvents} object on demand.
*/
@SuppressWarnings("serial")
private static class ApplicationEventsObjectFactory implements ObjectFactory<ApplicationEvents>, Serializable {
@Override
public ApplicationEvents getObject() {
return ApplicationEventsHolder.getRequiredApplicationEvents();
}
@Override
public String toString() {
return "Current ApplicationEvents";
}
}
}

View File

@ -0,0 +1,65 @@
/*
* 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.event;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.PayloadApplicationEvent;
/**
* Default implementation of {@link ApplicationEvents}.
*
* @author Oliver Drotbohm
* @author Sam Brannen
* @since 5.3.3
*/
class DefaultApplicationEvents implements ApplicationEvents {
private final List<ApplicationEvent> events = new ArrayList<>();
void addEvent(ApplicationEvent event) {
this.events.add(event);
}
@Override
public Stream<ApplicationEvent> stream() {
return this.events.stream();
}
@Override
public <T> Stream<T> stream(Class<T> type) {
return this.events.stream()
.map(this::unwrapPayloadEvent)
.filter(type::isInstance)
.map(type::cast);
}
@Override
public void clear() {
this.events.clear();
}
private Object unwrapPayloadEvent(Object source) {
return (PayloadApplicationEvent.class.isInstance(source) ?
((PayloadApplicationEvent<?>) source).getPayload() : source);
}
}

View File

@ -0,0 +1,49 @@
/*
* 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.event;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* {@code @RecordApplicationEvents} is a class-level annotation that is used to
* instruct the <em>Spring TestContext Framework</em> to record all
* {@linkplain org.springframework.context.ApplicationEvent application events}
* that are published in the {@link org.springframework.context.ApplicationContext
* ApplicationContext} during the execution of a single test.
*
* <p>The recorded events can be accessed via the {@link ApplicationEvents} API
* within your tests.
*
* <p>This annotation may be used as a <em>meta-annotation</em> to create custom
* <em>composed annotations</em>.
*
* @author Sam Brannen
* @since 5.3.3
* @see ApplicationEvents
* @see ApplicationEventsTestExecutionListener
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface RecordApplicationEvents {
}

View File

@ -52,6 +52,7 @@ import org.springframework.core.annotation.RepeatableContainers;
import org.springframework.lang.Nullable;
import org.springframework.test.context.TestConstructor;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.context.event.ApplicationEvents;
import org.springframework.test.context.support.PropertyProvider;
import org.springframework.test.context.support.TestConstructorUtils;
import org.springframework.util.Assert;
@ -218,6 +219,7 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
* invoked with a fallback {@link PropertyProvider} that delegates its lookup
* to {@link ExtensionContext#getConfigurationParameter(String)}.</li>
* <li>The parameter is of type {@link ApplicationContext} or a sub-type thereof.</li>
* <li>The parameter is of type {@link ApplicationEvents} or a sub-type thereof.</li>
* <li>{@link ParameterResolutionDelegate#isAutowirable} returns {@code true}.</li>
* </ol>
* <p><strong>WARNING</strong>: If a test class {@code Constructor} is annotated
@ -238,9 +240,19 @@ public class SpringExtension implements BeforeAllCallback, AfterAllCallback, Tes
extensionContext.getConfigurationParameter(propertyName).orElse(null);
return (TestConstructorUtils.isAutowirableConstructor(executable, testClass, junitPropertyProvider) ||
ApplicationContext.class.isAssignableFrom(parameter.getType()) ||
supportsApplicationEvents(parameterContext) ||
ParameterResolutionDelegate.isAutowirable(parameter, parameterContext.getIndex()));
}
private boolean supportsApplicationEvents(ParameterContext parameterContext) {
if (ApplicationEvents.class.isAssignableFrom(parameterContext.getParameter().getType())) {
Assert.isTrue(parameterContext.getDeclaringExecutable() instanceof Method,
"ApplicationEvents can only be injected into test and lifecycle methods");
return true;
}
return false;
}
/**
* Resolve a value for the {@link Parameter} in the supplied {@link ParameterContext} by
* retrieving the corresponding dependency from the test's {@link ApplicationContext}.

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.
@ -27,6 +27,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.event.ApplicationEventsTestExecutionListener;
import org.springframework.test.context.event.EventPublishingTestExecutionListener;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener;
@ -54,6 +55,7 @@ import org.springframework.test.context.web.ServletTestExecutionListener;
* <ul>
* <li>{@link org.springframework.test.context.web.ServletTestExecutionListener}
* <li>{@link org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener}
* <li>{@link org.springframework.test.context.event.ApplicationEventsTestExecutionListener}
* <li>{@link org.springframework.test.context.support.DependencyInjectionTestExecutionListener}
* <li>{@link org.springframework.test.context.support.DirtiesContextTestExecutionListener}
* <li>{@link org.springframework.test.context.event.EventPublishingTestExecutionListener}
@ -82,6 +84,7 @@ import org.springframework.test.context.web.ServletTestExecutionListener;
* @see TestExecutionListeners
* @see ServletTestExecutionListener
* @see DirtiesContextBeforeModesTestExecutionListener
* @see ApplicationEventsTestExecutionListener
* @see DependencyInjectionTestExecutionListener
* @see DirtiesContextTestExecutionListener
* @see EventPublishingTestExecutionListener
@ -90,8 +93,8 @@ import org.springframework.test.context.web.ServletTestExecutionListener;
*/
@RunWith(SpringRunner.class)
@TestExecutionListeners({ ServletTestExecutionListener.class, DirtiesContextBeforeModesTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
EventPublishingTestExecutionListener.class })
ApplicationEventsTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class, EventPublishingTestExecutionListener.class })
public abstract class AbstractJUnit4SpringContextTests implements ApplicationContextAware {
/**

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.
@ -27,6 +27,7 @@ import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.lang.Nullable;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
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.DependencyInjectionTestExecutionListener;
@ -62,6 +63,7 @@ import org.springframework.util.Assert;
* <ul>
* <li>{@link org.springframework.test.context.web.ServletTestExecutionListener}
* <li>{@link org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener}
* <li>{@link org.springframework.test.context.event.ApplicationEventsTestExecutionListener}</li>
* <li>{@link org.springframework.test.context.support.DependencyInjectionTestExecutionListener}
* <li>{@link org.springframework.test.context.support.DirtiesContextTestExecutionListener}
* <li>{@link org.springframework.test.context.transaction.TransactionalTestExecutionListener}
@ -100,8 +102,8 @@ import org.springframework.util.Assert;
* @see org.springframework.test.jdbc.JdbcTestUtils
* @see org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests
*/
@TestExecutionListeners(listeners = { ServletTestExecutionListener.class,
DirtiesContextBeforeModesTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,
@TestExecutionListeners(listeners = { ServletTestExecutionListener.class, DirtiesContextBeforeModesTestExecutionListener.class,
ApplicationEventsTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class,
SqlScriptsTestExecutionListener.class, EventPublishingTestExecutionListener.class }, inheritListeners = false)
@Transactional

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.
@ -36,6 +36,7 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestContext;
import org.springframework.test.context.TestContextManager;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.event.ApplicationEventsTestExecutionListener;
import org.springframework.test.context.event.EventPublishingTestExecutionListener;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener;
@ -64,6 +65,7 @@ import org.springframework.test.context.web.ServletTestExecutionListener;
* <ul>
* <li>{@link org.springframework.test.context.web.ServletTestExecutionListener}
* <li>{@link org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener}
* <li>{@link org.springframework.test.context.event.ApplicationEventsTestExecutionListener}
* <li>{@link org.springframework.test.context.support.DependencyInjectionTestExecutionListener}
* <li>{@link org.springframework.test.context.support.DirtiesContextTestExecutionListener}
* <li>{@link org.springframework.test.context.event.EventPublishingTestExecutionListener}
@ -78,6 +80,7 @@ import org.springframework.test.context.web.ServletTestExecutionListener;
* @see TestExecutionListeners
* @see ServletTestExecutionListener
* @see DirtiesContextBeforeModesTestExecutionListener
* @see ApplicationEventsTestExecutionListener
* @see DependencyInjectionTestExecutionListener
* @see DirtiesContextTestExecutionListener
* @see EventPublishingTestExecutionListener
@ -85,8 +88,8 @@ import org.springframework.test.context.web.ServletTestExecutionListener;
* @see org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests
*/
@TestExecutionListeners({ ServletTestExecutionListener.class, DirtiesContextBeforeModesTestExecutionListener.class,
DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class,
EventPublishingTestExecutionListener.class })
ApplicationEventsTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class, EventPublishingTestExecutionListener.class })
public abstract class AbstractTestNGSpringContextTests implements IHookable, ApplicationContextAware {
/** Logger available to subclasses. */

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.
@ -26,6 +26,7 @@ import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
import org.springframework.lang.Nullable;
import org.springframework.test.context.TestExecutionListeners;
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.DependencyInjectionTestExecutionListener;
@ -61,6 +62,7 @@ import org.springframework.util.Assert;
* <ul>
* <li>{@link org.springframework.test.context.web.ServletTestExecutionListener}
* <li>{@link org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener}
* <li>{@link org.springframework.test.context.event.ApplicationEventsTestExecutionListener}</li>
* <li>{@link org.springframework.test.context.support.DependencyInjectionTestExecutionListener}
* <li>{@link org.springframework.test.context.support.DirtiesContextTestExecutionListener}
* <li>{@link org.springframework.test.context.transaction.TransactionalTestExecutionListener}
@ -84,8 +86,8 @@ import org.springframework.util.Assert;
* @see org.springframework.test.jdbc.JdbcTestUtils
* @see org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests
*/
@TestExecutionListeners(listeners = { ServletTestExecutionListener.class,
DirtiesContextBeforeModesTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,
@TestExecutionListeners(listeners = { ServletTestExecutionListener.class, DirtiesContextBeforeModesTestExecutionListener.class,
ApplicationEventsTestExecutionListener.class, DependencyInjectionTestExecutionListener.class,
DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class,
SqlScriptsTestExecutionListener.class, EventPublishingTestExecutionListener.class }, inheritListeners = false)
@Transactional

View File

@ -3,6 +3,7 @@
org.springframework.test.context.TestExecutionListener = \
org.springframework.test.context.web.ServletTestExecutionListener,\
org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener,\
org.springframework.test.context.event.ApplicationEventsTestExecutionListener,\
org.springframework.test.context.support.DependencyInjectionTestExecutionListener,\
org.springframework.test.context.support.DirtiesContextTestExecutionListener,\
org.springframework.test.context.transaction.TransactionalTestExecutionListener,\

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;
}
}
}

View File

@ -414,6 +414,7 @@ Spring's testing annotations include the following:
* <<spring-testing-annotation-dynamicpropertysource>>
* <<spring-testing-annotation-dirtiescontext>>
* <<spring-testing-annotation-testexecutionlisteners>>
* <<spring-testing-annotation-recordapplicationevents>>
* <<spring-testing-annotation-commit>>
* <<spring-testing-annotation-rollback>>
* <<spring-testing-annotation-beforetransaction>>
@ -1134,6 +1135,19 @@ superclasses or enclosing classes. See
{api-spring-framework}/test/context/TestExecutionListeners.html[`@TestExecutionListeners`
javadoc] for an example and further details.
[[spring-testing-annotation-recordapplicationevents]]
===== `@RecordApplicationEvents`
`@RecordApplicationEvents` is a class-level annotation that is used to instruct the
_Spring TestContext Framework_ to record all application events that are published in the
`ApplicationContext` during the execution of a single test.
The recorded events can be accessed via the `ApplicationEvents` API within tests.
See <<testcontext-application-events>> and the
{api-spring-framework}/test/context/event/RecordApplicationEvents.html[`@RecordApplicationEvents`
javadoc] for an example and further details.
[[spring-testing-annotation-commit]]
===== `@Commit`
@ -1880,6 +1894,7 @@ following annotations.
* <<spring-testing-annotation-dynamicpropertysource>>
* <<spring-testing-annotation-dirtiescontext>>
* <<spring-testing-annotation-testexecutionlisteners>>
* <<spring-testing-annotation-recordapplicationevents>>
* <<testcontext-tx,`@Transactional`>>
* <<spring-testing-annotation-commit>>
* <<spring-testing-annotation-rollback>>
@ -2401,6 +2416,8 @@ by default, exactly in the following order:
`WebApplicationContext`.
* `DirtiesContextBeforeModesTestExecutionListener`: Handles the `@DirtiesContext`
annotation for "`before`" modes.
* `ApplicationEventsTestExecutionListener`: Provides support for
<<testcontext-application-events, `ApplicationEvents`>>.
* `DependencyInjectionTestExecutionListener`: Provides dependency injection for the test
instance.
* `DirtiesContextTestExecutionListener`: Handles the `@DirtiesContext` annotation for
@ -2547,6 +2564,95 @@ be replaced with the following:
}
----
[[testcontext-application-events]]
==== Application Events
Since Spring Framework 5.3.3, the TestContext framework provides support for recording
<<core.adoc#context-functionality-events, 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 you to process the events as a
`java.util.Stream`.
To use `ApplicationEvents` in your tests, do the following.
* Ensure that your test class is annotated or meta-annotated with
<<spring-testing-annotation-recordapplicationevents>>.
* Ensure that the `ApplicationEventsTestExecutionListener` is registered. Note, however,
that `ApplicationEventsTestExecutionListener` is registered by default and only needs
to be manually registered if you have custom configuration via
`@TestExecutionListeners` that does not include the default listeners.
* Annotate a field of type `ApplicationEvents` with `@Autowired` and use that instance of
`ApplicationEvents` in your test and lifecycle methods (such as `@BeforeEach` and
`@AfterEach` methods in JUnit Jupiter).
** When using the <<testcontext-junit-jupiter-extension>>, you may declare a method
parameter of type `ApplicationEvents` in a test or lifecycle method as an alternative
to an `@Autowired` field in the test class.
The following test class uses the `SpringExtension` for JUnit Jupiter and
https://assertj.github.io/doc/[AssertJ] to assert the types of application events
published while invoking a method in a Spring-managed component:
// Don't use "quotes" in the "subs" section because of the asterisks in /* ... */
[source,java,indent=0,subs="verbatim",role="primary"]
.Java
----
@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents // <1>
class OrderServiceTests {
@Autowired
OrderService orderService;
@Autowired
ApplicationEvents events; // <2>
@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(); // <3>
assertThat(numEvents).isEqualTo(1);
}
}
----
<1> Annotate the test class with `@RecordApplicationEvents`.
<2> Inject the `ApplicationEvents` instance for the current test.
<3> Use the `ApplicationEvents` API to count how many `OrderSubmitted` events were published.
// Don't use "quotes" in the "subs" section because of the asterisks in /* ... */
[source,kotlin,indent=0,subs="verbatim",role="secondary"]
.Kotlin
----
@SpringJUnitConfig(/* ... */)
@RecordApplicationEvents // <1>
class OrderServiceTests {
@Autowired
lateinit var orderService: OrderService
@Autowired
lateinit var events: ApplicationEvents // <2>
@Test
fun submitOrder() {
// Invoke method in OrderService that publishes an event
orderService.submitOrder(Order(/* ... */))
// Verify that an OrderSubmitted event was published
val numEvents = events.stream(OrderSubmitted::class).count() // <3>
assertThat(numEvents).isEqualTo(1)
}
}
----
<1> Annotate the test class with `@RecordApplicationEvents`.
<2> Inject the `ApplicationEvents` instance for the current test.
<3> Use the `ApplicationEvents` API to count how many `OrderSubmitted` events were published.
See the
{api-spring-framework}/test/context/event/ApplicationEvents.html[`ApplicationEvents`
javadoc] for further details regarding the `ApplicationEvents` API.
[[testcontext-test-execution-events]]
==== Test Execution Events
@ -7705,7 +7811,7 @@ to create a message, as the following example shows:
----
Finally, we can verify that a new message was created successfully. The following
assertions use the https://joel-costigliola.github.io/assertj/[AssertJ] library:
assertions use the https://assertj.github.io/doc/[AssertJ] library:
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
.Java
@ -8172,7 +8278,7 @@ annotation to look up our submit button with a `css` selector (*input[type=submi
Finally, we can verify that a new message was created successfully. The following
assertions use the https://joel-costigliola.github.io/assertj/[AssertJ] assertion library:
assertions use the https://assertj.github.io/doc/[AssertJ] assertion library:
[source,java,indent=0,subs="verbatim,quotes",role="primary"]
.Java
@ -8618,7 +8724,7 @@ See the following resources for more information about testing:
* https://testng.org/[TestNG]: A testing framework inspired by JUnit with added support
for test groups, data-driven testing, distributed testing, and other features. Supported
in the <<testcontext-framework, Spring TestContext Framework>>
* https://joel-costigliola.github.io/assertj/[AssertJ]: "`Fluent assertions for Java`",
* https://assertj.github.io/doc/[AssertJ]: "`Fluent assertions for Java`",
including support for Java 8 lambdas, streams, and other features.
* https://en.wikipedia.org/wiki/Mock_Object[Mock Objects]: Article in Wikipedia.
* http://www.mockobjects.com/[MockObjects.com]: Web site dedicated to mock objects, a