【发布时间】:2026-01-12 16:40:01
【问题描述】:
我正在编写一个新应用程序并尝试使用 cucumber 和 Spring Boot 1.4 进行 BDD。工作代码如下:
@SpringBootApplication
public class Application {
@Bean
MyService myService() {
return new MyService();
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
public class MyService {}
测试代码如下:
@RunWith(Cucumber.class)
public class RunFeatures {}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class, loader = SpringApplicationContextLoader.class)
public class MyStepDef {
@Autowired
MyService myService;
@Given("^Some initial condition$")
public void appIsStarted() throws Throwable {
if (service == null) throw new Exception("Dependency not injected!");
System.out.println("App started");
}
@Then("^Nothing happens$")
public void thereShouldBeNoException() throws Throwable {
System.out.println("Test passed");
}
}
特征文件如下图:
Feature: Test Cucumber with spring
Scenario: First Scenario
Given Some initial condition
Then Nothing happens
当我按原样运行上述程序时,一切正常,并且依赖项(MyService)被注入到 MyStepDef 中,没有任何问题。
如果我替换此代码:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class, loader = SpringApplicationContextLoader.class)
使用下面的代码(在 Spring Boot 1.4 中处理它的新方法):
@RunWith(SpringRunner.class)
@SpringBootTest
然后依赖项(MyService)永远不会被注入。也许我错过了什么?
提前感谢您的帮助!!!
【问题讨论】:
-
我也有同样的问题
-
cucumber-spring 中有问题的代码似乎是这样的:github.com/cucumber/cucumber-jvm/blob/master/spring/src/main/…
标签: java spring-boot cucumber-jvm