![](/img/trans.png)
[英]JUnit Spring 4 MVC Integration Test Failing with BeanCreationException: Error creating bean
[英]Error creating bean in JUnit test in Spring Boot
我在Spring Boot中创建应用程序。 我创建了这样的服务:
@Service
public class MyService {
@Value("${myprops.hostname}")
private String host;
public void callEndpoint() {
String endpointUrl = this.host + "/endpoint";
System.out.println(endpointUrl);
}
}
此服务将连接到REST端点到将部署的其他应用程序(由我开发)。 这就是我想在application.properties文件(-default,-qa,-dev)中自定义主机名的原因。
我的应用程序构建和工作正常。 我通过创建调用此服务的控制器来测试它,并使用application.properties中的正确属性填充host
字段。
当我尝试为此类编写测试时,会出现问题。 当我尝试这种方法时:
@RunWith(SpringRunner.class)
public class MyServiceTest {
@Autowired
private MyService myService;
@Test
public void callEndpoint() {
myService.callEndpoint();
}
}
我收到例外:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.ge.bm.wip.comp.processor.service.MyServiceTest': Unsatisfied dependency expressed through field 'myService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.ge.bm.wip.comp.processor.service.MyService' available: expected at least 1 bean which qualifies as autowire candidate.
还有一些嵌套异常。 我可以发布它们,如果它会有所帮助。 我想由于某种原因,SpringRunner不会在Spring上下文中启动此测试,因此无法看到bean MyService。
有谁知道它是如何修复的? 我试过正常的初始化:
private MyService myService = new myService();
但是host
字段为null
您还必须使用@SpringBootTest
注释您的测试。
尝试:
@SpringBootTest
@RunWith(SpringRunner.class)
public class MyServiceTest {
@Autowired
private MyService myService;
@Test
public void callEndpoint() {
myService.callEndpoint();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.