简体   繁体   English

黄瓜+弹簧:如何通过测试触发SmartLifecycle事件?

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

I have a spring boot application with cucumber.我有一个带有黄瓜的弹簧启动应用程序。 I would like to perform certain events within the test BEFORE the start-SmartLifecycle event of the beans is called.我想在调用 bean 的 start-SmartLifecycle 事件之前在测试中执行某些事件。

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

Is there any way to achieve this?有没有办法实现这一目标? By default, it looks like Spring initializes and starts all the beans before any Cucumber statements are executed.默认情况下,Spring 似乎在执行任何 Cucumber 语句之前初始化并启动所有 bean。

Example:例子:

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 definitions file:黄瓜定义文件:

 @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() { ... }
 }

You can't test a dependency injection container while using that same container to inject dependencies into your test.您无法在使用同一容器将依赖项注入测试时测试依赖项注入容器。 Injecting dependencies requires the application context to have been refreshed already.注入依赖项需要已经刷新应用程序上下文。

So you have to create an instance of the ApplicationContext manually and manage it's life-cycle yourself.因此,您必须手动创建ApplicationContext的实例并自己管理它的生命周期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM