gpt4 book ai didi

java - 带有 Spring Boot 1.4 : Dependencies not injected when using @SpringBootTest and @RunWith(SpringRunner. 类的 cucumber )

转载 作者:搜寻专家 更新时间:2023-10-30 21:02:43 25 4
gpt4 key购买 nike

我正在编写一个新应用程序并尝试使用 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) 毫无问题地注入(inject)到 MyStepDef 中。

如果我替换这段代码:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Application.class, loader = SpringApplicationContextLoader.class)

使用下面的代码(在 Spring Boot 1.4 中处理它的新方法):

@RunWith(SpringRunner.class)
@SpringBootTest

然后依赖项 (MyService) 永远不会被注入(inject)。我是否遗漏了什么?

在此先感谢您的帮助!!!

最佳答案

我遇到了同样的问题。上面的评论让我找到了解决方案

The problematic code in cucumber-spring seems to be this github.com/cucumber/cucumber-jvm/blob/master/spring/src/main‌​/…

添加注释 @ContextConfiguration 后,测试按预期工作。

所以我得到的是以下...

@RunWith(Cucumber.class)
@CucumberOptions(plugin = {"json:target/cucumber.json", "pretty"}, features = "src/test/features")
public class CucumberTest {
}

@ContextConfiguration
@SpringBootTest
public abstract class StepDefs {
}

public class MyStepDefs extends StepDefs {

@Inject
Service service;

@Inject
Repository repository;

[...]

}

希望对你有帮助

关于java - 带有 Spring Boot 1.4 : Dependencies not injected when using @SpringBootTest and @RunWith(SpringRunner. 类的 cucumber ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38836337/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com