I want to integration test a Spring Boot 1.5.4 service that uses an @EventListener. My problem is: when the test is run, the events are correctly published, but they are not consumed.
My ultimate purpose is to use a @TransactionEventListener, but for simplicity I start with an @EventListener.
Here is my service class:
@Service
public class MyService {
private static final Logger logger = // ...
private final ApplicationEventPublisher eventPublisher;
@Autowired
public MyService(ApplicationEventPublisher eventPublisher) {
this.eventPublisher = eventPublisher;
}
@Transactional
public void publish() {
logger.warn("Publishing!");
eventPublisher.publishEvent(new MyEvent());
}
// @TransactionalEventListener
@EventListener
public void consume(MyEvent event) {
logger.warn("Consuming!"); // this is never executed in the test
}
public static class MyEvent {
}
}
Here is my JUnit test class:
@RunWith(SpringRunner.class)
@SpringBootTest
@SpringBootConfiguration
public class MyServiceIT {
@Autowired
MyService myService;
@Test
public void doSomething() {
myService.publish();
}
static class TestConfig {
@Bean
public MyService myService() {
return new MyService(eventPublisher());
}
@Bean
public ApplicationEventPublisher eventPublisher() {
ApplicationEventPublisher ctx = new GenericApplicationContext();
((AbstractApplicationContext)ctx).refresh();
return ctx;
}
}
}
Note: the call to refresh() prevents an IllegalStateException with message "ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context" from occurring.
Does anyone have a clue? Many thanks in advance.