summaryrefslogtreecommitdiff
path: root/spring-context/src/test/java/org/springframework/context/event/ApplicationListenerMethodAdapterTests.java
blob: b9cc4dd0d80a473cfd13f8b52dbbf523b592fe55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
/*
 * Copyright 2002-2015 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
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.context.event;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.UndeclaredThrowableException;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

import org.springframework.aop.framework.ProxyFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.PayloadApplicationEvent;
import org.springframework.core.ResolvableType;
import org.springframework.core.ResolvableTypeProvider;
import org.springframework.core.annotation.Order;
import org.springframework.util.ReflectionUtils;

import static org.hamcrest.Matchers.*;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

/**
 * @author Stephane Nicoll
 */
public class ApplicationListenerMethodAdapterTests extends AbstractApplicationEventListenerTests {

	@Rule
	public final ExpectedException thrown = ExpectedException.none();

	private final SampleEvents sampleEvents = spy(new SampleEvents());

	private final ApplicationContext context = mock(ApplicationContext.class);

	@Test
	public void rawListener() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleRaw", ApplicationEvent.class);
		supportsEventType(true, method, getGenericApplicationEventType("applicationEvent"));
	}

	@Test
	public void rawListenerWithGenericEvent() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleRaw", ApplicationEvent.class);
		supportsEventType(true, method, getGenericApplicationEventType("stringEvent"));
	}

	@Test
	public void genericListener() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleGenericString", GenericTestEvent.class);
		supportsEventType(true, method, getGenericApplicationEventType("stringEvent"));
	}

	@Test
	public void genericListenerWrongParameterizedType() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleGenericString", GenericTestEvent.class);
		supportsEventType(false, method, getGenericApplicationEventType("longEvent"));
	}

	@Test
	public void listenerWithPayloadAndGenericInformation() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleString", String.class);
		supportsEventType(true, method, createGenericEventType(String.class));
	}

	@Test
	public void listenerWithInvalidPayloadAndGenericInformation() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleString", String.class);
		supportsEventType(false, method, createGenericEventType(Integer.class));
	}

	@Test
	public void listenerWithPayloadTypeErasure() { // Always accept such event when the type is unknown
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleString", String.class);
		supportsEventType(true, method, ResolvableType.forClass(PayloadApplicationEvent.class));
	}

	@Test
	public void listenerWithSubTypeSeveralGenerics() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleString", String.class);
		supportsEventType(true, method, ResolvableType.forClass(PayloadTestEvent.class));
	}

	@Test
	public void listenerWithSubTypeSeveralGenericsResolved() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleString", String.class);
		supportsEventType(true, method, ResolvableType.forClass(PayloadStringTestEvent.class));
	}

	@Test
	public void listenerWithAnnotationValue() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleStringAnnotationValue");
		supportsEventType(true, method, createGenericEventType(String.class));
	}

	@Test
	public void listenerWithAnnotationClasses() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleStringAnnotationClasses");
		supportsEventType(true, method, createGenericEventType(String.class));
	}

	@Test
	public void listenerWithAnnotationValueAndParameter() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleStringAnnotationValueAndParameter", String.class);
		supportsEventType(true, method, createGenericEventType(String.class));
	}

	@Test
	public void listenerWithSeveralTypes() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleStringOrInteger");
		supportsEventType(true, method, createGenericEventType(String.class));
		supportsEventType(true, method, createGenericEventType(Integer.class));
		supportsEventType(false, method, createGenericEventType(Double.class));
	}

	@Test
	public void listenerWithTooManyParameters() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"tooManyParameters", String.class, String.class);

		thrown.expect(IllegalStateException.class);
		createTestInstance(method);
	}

	@Test
	public void listenerWithNoParameter() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"noParameter");

		thrown.expect(IllegalStateException.class);
		createTestInstance(method);
	}

	@Test
	public void listenerWithMoreThanOneParameter() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"moreThanOneParameter", String.class, Integer.class);

		thrown.expect(IllegalStateException.class);
		createTestInstance(method);
	}

	@Test
	public void defaultOrder() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleGenericString", GenericTestEvent.class);
		ApplicationListenerMethodAdapter adapter = createTestInstance(method);
		assertEquals(0, adapter.getOrder());
	}

	@Test
	public void specifiedOrder() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleRaw", ApplicationEvent.class);
		ApplicationListenerMethodAdapter adapter = createTestInstance(method);
		assertEquals(42, adapter.getOrder());
	}

	@Test
	public void invokeListener() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleGenericString", GenericTestEvent.class);
		GenericTestEvent<String> event = createGenericTestEvent("test");
		invokeListener(method, event);
		verify(this.sampleEvents, times(1)).handleGenericString(event);
	}

	@Test
	public void invokeListenerWithGenericEvent() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleGenericString", GenericTestEvent.class);
		GenericTestEvent<String> event = new SmartGenericTestEvent<>(this, "test");
		invokeListener(method, event);
		verify(this.sampleEvents, times(1)).handleGenericString(event);
	}

	@Test
	public void invokeListenerWithGenericPayload() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleGenericStringPayload", EntityWrapper.class);
		EntityWrapper<String> payload = new EntityWrapper<>("test");
		invokeListener(method, new PayloadApplicationEvent<>(this, payload));
		verify(this.sampleEvents, times(1)).handleGenericStringPayload(payload);
	}

	@Test
	public void invokeListenerWithWrongGenericPayload() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleGenericStringPayload", EntityWrapper.class);
		EntityWrapper<Integer> payload = new EntityWrapper<>(123);
		invokeListener(method, new PayloadApplicationEvent<>(this, payload));
		verify(this.sampleEvents, times(0)).handleGenericStringPayload(any());
	}

	@Test
	public void invokeListenerWithAnyGenericPayload() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleGenericAnyPayload", EntityWrapper.class);
		EntityWrapper<String> payload = new EntityWrapper<>("test");
		invokeListener(method, new PayloadApplicationEvent<>(this, payload));
		verify(this.sampleEvents, times(1)).handleGenericAnyPayload(payload);
	}

	@Test
	public void invokeListenerRuntimeException() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"generateRuntimeException", GenericTestEvent.class);
		GenericTestEvent<String> event = createGenericTestEvent("fail");

		thrown.expect(IllegalStateException.class);
		thrown.expectMessage("Test exception");
		thrown.expectCause(is(isNull(Throwable.class)));
		invokeListener(method, event);
	}

	@Test
	public void invokeListenerCheckedException() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"generateCheckedException", GenericTestEvent.class);
		GenericTestEvent<String> event = createGenericTestEvent("fail");

		thrown.expect(UndeclaredThrowableException.class);
		thrown.expectCause(is(instanceOf(IOException.class)));
		invokeListener(method, event);
	}

	@Test
	public void invokeListenerInvalidProxy() {
		Object target = new InvalidProxyTestBean();
		ProxyFactory proxyFactory = new ProxyFactory();
		proxyFactory.setTarget(target);
		proxyFactory.addInterface(SimpleService.class);
		Object bean = proxyFactory.getProxy(getClass().getClassLoader());

		Method method = ReflectionUtils.findMethod(InvalidProxyTestBean.class, "handleIt2", ApplicationEvent.class);
		StaticApplicationListenerMethodAdapter listener =
				new StaticApplicationListenerMethodAdapter(method, bean);
		thrown.expect(IllegalStateException.class);
		thrown.expectMessage("handleIt2");
		listener.onApplicationEvent(createGenericTestEvent("test"));
	}

	@Test
	public void invokeListenerWithPayload() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleString", String.class);
		PayloadApplicationEvent<String> event = new PayloadApplicationEvent<>(this, "test");
		invokeListener(method, event);
		verify(this.sampleEvents, times(1)).handleString("test");
	}

	@Test
	public void invokeListenerWithPayloadWrongType() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleString", String.class);
		PayloadApplicationEvent<Long> event = new PayloadApplicationEvent<>(this, 123L);
		invokeListener(method, event);
		verify(this.sampleEvents, never()).handleString(anyString());
	}

	@Test
	public void invokeListenerWithAnnotationValue() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleStringAnnotationClasses");
		PayloadApplicationEvent<String> event = new PayloadApplicationEvent<>(this, "test");
		invokeListener(method, event);
		verify(this.sampleEvents, times(1)).handleStringAnnotationClasses();
	}

	@Test
	public void invokeListenerWithAnnotationValueAndParameter() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleStringAnnotationValueAndParameter", String.class);
		PayloadApplicationEvent<String> event = new PayloadApplicationEvent<>(this, "test");
		invokeListener(method, event);
		verify(this.sampleEvents, times(1)).handleStringAnnotationValueAndParameter("test");
	}

	@Test
	public void invokeListenerWithSeveralTypes() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleStringOrInteger");
		PayloadApplicationEvent<String> event = new PayloadApplicationEvent<>(this, "test");
		invokeListener(method, event);
		verify(this.sampleEvents, times(1)).handleStringOrInteger();
		PayloadApplicationEvent<Integer> event2 = new PayloadApplicationEvent<>(this, 123);
		invokeListener(method, event2);
		verify(this.sampleEvents, times(2)).handleStringOrInteger();
		PayloadApplicationEvent<Double> event3 = new PayloadApplicationEvent<>(this, 23.2);
		invokeListener(method, event3);
		verify(this.sampleEvents, times(2)).handleStringOrInteger();
	}


	@Test
	public void beanInstanceRetrievedAtEveryInvocation() {
		Method method = ReflectionUtils.findMethod(SampleEvents.class,
				"handleGenericString", GenericTestEvent.class);
		when(this.context.getBean("testBean")).thenReturn(this.sampleEvents);
		ApplicationListenerMethodAdapter listener = new ApplicationListenerMethodAdapter(
				"testBean", GenericTestEvent.class, method);
		listener.init(this.context, new EventExpressionEvaluator());
		GenericTestEvent<String> event = createGenericTestEvent("test");


		listener.onApplicationEvent(event);
		verify(this.sampleEvents, times(1)).handleGenericString(event);
		verify(this.context, times(1)).getBean("testBean");

		listener.onApplicationEvent(event);
		verify(this.sampleEvents, times(2)).handleGenericString(event);
		verify(this.context, times(2)).getBean("testBean");
	}

	private void supportsEventType(boolean match, Method method, ResolvableType eventType) {
		ApplicationListenerMethodAdapter adapter = createTestInstance(method);
		assertEquals("Wrong match for event '" + eventType + "' on " + method,
				match, adapter.supportsEventType(eventType));
	}

	private void invokeListener(Method method, ApplicationEvent event) {
		ApplicationListenerMethodAdapter adapter = createTestInstance(method);
		adapter.onApplicationEvent(event);
	}

	private ApplicationListenerMethodAdapter createTestInstance(Method method) {
		return new StaticApplicationListenerMethodAdapter(method, this.sampleEvents);
	}

	private ResolvableType createGenericEventType(Class<?> payloadType) {
		return ResolvableType.forClassWithGenerics(PayloadApplicationEvent.class, payloadType);
	}

	private static class StaticApplicationListenerMethodAdapter
			extends ApplicationListenerMethodAdapter {

		private final Object targetBean;

		public StaticApplicationListenerMethodAdapter(Method method, Object targetBean) {
			super("unused", targetBean.getClass(), method);
			this.targetBean = targetBean;
		}

		@Override
		public Object getTargetBean() {
			return targetBean;
		}
	}


	private static class SampleEvents {


		@EventListener
		@Order(42)
		public void handleRaw(ApplicationEvent event) {
		}

		@EventListener
		public void handleGenericString(GenericTestEvent<String> event) {
		}

		@EventListener
		public void handleString(String payload) {
		}

		@EventListener(String.class)
		public void handleStringAnnotationValue() {
		}

		@EventListener(classes = String.class)
		public void handleStringAnnotationClasses() {
		}

		@EventListener(String.class)
		public void handleStringAnnotationValueAndParameter(String payload) {
		}

		@EventListener({String.class, Integer.class})
		public void handleStringOrInteger() {
		}

		@EventListener({String.class, Integer.class})
		public void handleStringOrIntegerWithParam(String invalid) {
		}

		@EventListener
		public void handleGenericStringPayload(EntityWrapper<String> event) {
		}

		@EventListener
		public void handleGenericAnyPayload(EntityWrapper<?> event) {
		}

		@EventListener
		public void tooManyParameters(String event, String whatIsThis) {
		}

		@EventListener
		public void noParameter() {
		}

		@EventListener
		public void moreThanOneParameter(String foo, Integer bar) {
		}

		@EventListener
		public void generateRuntimeException(GenericTestEvent<String> event) {
			if ("fail".equals(event.getPayload())) {
				throw new IllegalStateException("Test exception");
			}
		}

		@EventListener
		public void generateCheckedException(GenericTestEvent<String> event) throws IOException {
			if ("fail".equals(event.getPayload())) {
				throw new IOException("Test exception");
			}
		}
	}

	interface SimpleService {

		void handleIt(ApplicationEvent event);

	}

	private static class EntityWrapper<T> implements ResolvableTypeProvider {
		private final T entity;

		public EntityWrapper(T entity) {
			this.entity = entity;
		}

		@Override
		public ResolvableType getResolvableType() {
			return ResolvableType.forClassWithGenerics(getClass(), this.entity.getClass());
		}
	}

	static class InvalidProxyTestBean implements SimpleService {

		@Override
		public void handleIt(ApplicationEvent event) {
		}

		@EventListener
		public void handleIt2(ApplicationEvent event) {
		}
	}

	@SuppressWarnings({"unused", "serial"})
	static class PayloadTestEvent<V, T> extends PayloadApplicationEvent<T> {

		private final V something;

		public PayloadTestEvent(Object source, T payload, V something) {
			super(source, payload);
			this.something = something;
		}
	}

	@SuppressWarnings({ "serial" })
	static class PayloadStringTestEvent extends PayloadTestEvent<Long, String> {
		public PayloadStringTestEvent(Object source, String payload, Long something) {
			super(source, payload, something);
		}
	}

}