我正在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
答案 0 :(得分:9)
您还必须使用@SpringBootTest
注释您的测试。
尝试:
@SpringBootTest
@RunWith(SpringRunner.class)
public class MyServiceTest {
@Autowired
private MyService myService;
@Test
public void callEndpoint() {
myService.callEndpoint();
}
}