Spring ApplicationEventPublisher的单元测试无法使用事件

时间:2018-01-16 17:27:19

标签: spring-boot spring-boot-test

我想集成测试使用@EventListener的Spring Boot 1.5.4服务。我的问题是:当测试运行时,事件被正确发布,但它们不被消耗。

我的最终目的是使用@TransactionEventListener,但为了简单起见,我从@EventListener开始。

这是我的服务类:

@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 {
  }
}

这是我的JUnit测试类:

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

注意:对refresh()的调用可防止IllegalStateException,消息" ApplicationEventMulticaster未初始化 - 调用' refresh'在通过上下文组播事件之前#34;从发生。

有没有人有线索?非常感谢提前。

1 个答案:

答案 0 :(得分:0)

对于记录,解决方案是:将事件使用者方法保留在除事件生成器方法之外的另一个bean中。也就是说,extract方法从MyService类中消耗(MyEvent)到一个新的@Service类MyConsumer。