Introduce generalized MethodFailureEvent for use in EventPublicationInterceptor

Closes gh-36072
This commit is contained in:
Juergen Hoeller
2025-12-24 18:50:04 +01:00
parent 214cb2c1e1
commit 08104100d3
5 changed files with 162 additions and 46 deletions
@@ -59,6 +59,7 @@ import org.springframework.scheduling.support.TaskUtils;
import org.springframework.util.ReflectionUtils;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
import static org.assertj.core.api.Assertions.assertThatRuntimeException;
import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.BDDMockito.given;
@@ -298,7 +299,7 @@ class ApplicationContextEventTests extends AbstractApplicationEventListenerTests
}
@Test
void testEventPublicationInterceptor() throws Throwable {
void testEventPublicationInterceptorWithEventClass() throws Throwable {
MethodInvocation invocation = mock();
ApplicationContext ctx = mock();
@@ -313,6 +314,36 @@ class ApplicationContextEventTests extends AbstractApplicationEventListenerTests
verify(ctx).publishEvent(isA(MyEvent.class));
}
@Test
void testEventPublicationInterceptorWithEventFactory() throws Throwable {
MethodInvocation invocation = mock();
ApplicationContext ctx = mock();
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventFactory(inv -> new MyEvent(invocation.getThis()));
interceptor.setApplicationEventPublisher(ctx);
interceptor.afterPropertiesSet();
given(invocation.proceed()).willReturn(new Object());
given(invocation.getThis()).willReturn(new Object());
interceptor.invoke(invocation);
verify(ctx).publishEvent(isA(MyEvent.class));
}
@Test
void testEventPublicationInterceptorWithMethodFailure() throws Throwable {
MethodInvocation invocation = mock();
ApplicationContext ctx = mock();
EventPublicationInterceptor interceptor = new EventPublicationInterceptor();
interceptor.setApplicationEventPublisher(ctx);
interceptor.afterPropertiesSet();
given(invocation.proceed()).willThrow(new IllegalStateException());
assertThatIllegalStateException().isThrownBy(() -> interceptor.invoke(invocation));
verify(ctx).publishEvent(isA(MethodFailureEvent.class));
}
@Test
void listenersInApplicationContext() {
StaticApplicationContext context = new StaticApplicationContext();
@@ -53,14 +53,16 @@ class EventPublicationInterceptorTests {
@Test
void withNoApplicationEventClassSupplied() {
void withNoApplicationEventPublisherSupplied() {
this.interceptor.setApplicationEventPublisher(null);
assertThatIllegalArgumentException().isThrownBy(interceptor::afterPropertiesSet);
}
@SuppressWarnings("unchecked")
@Test
void withNonApplicationEventClassSupplied() {
assertThatIllegalArgumentException().isThrownBy(() -> {
interceptor.setApplicationEventClass(getClass());
interceptor.setApplicationEventClass((Class) getClass());
interceptor.afterPropertiesSet();
});
}