我在Spring Boot中創建應用程序。我創建的服務,看起來是這樣:在Spring啓動JUnit測試中創建bean時出錯
@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