Cucumber + spring: 如何通过测试触发SmartLifecycle事件?

Cucumber + spring: How to trigger SmartLifecycle events through tests?

我有一个 spring 带有黄瓜的启动应用程序。我想在调用 bean 的 start-SmartLifecycle 事件之前在测试中执行某些事件。

Given Something that needs to happen before beans are started
And Beans start up now
Then Life is good

有什么办法可以实现吗? 默认情况下,看起来 Spring 在执行任何 Cucumber 语句之前初始化并启动所有 bean。

示例:

class Context {
  @Bean
  SomeBean someBean() { return new SomeBean(); }
}

class SomeBean implements SmartLifecycle {
  @Override
  void start() {
    // some meaningful work that depends on setup that needs to be done beforehand
  }
  // rest of interface implementation
}

Cucumber 定义文件:

 @ContextConfiguration(classes = Context.class)
 class CucumberFeatures {
   @Autowired
   private SomeBean someBean;

   @Given("Something that needs to happen before beans are started")
   public void something() {
     // ...
   }

   @Given("Beans start up now")
   public void beansStarted() {
     // This should start beans in their defined order now
   }

   @Then("Life is good")
   public void lifeIsGood() { ... }
 }

您无法在使用同一容器将依赖项注入测试时测试依赖项注入容器。注入依赖项需要应用程序上下文已经刷新。

因此您必须手动创建 ApplicationContext 的实例并自行管理它的生命周期。