在Spring Boot中的JUnit测试中创建bean时出错

Zyc*_*hoo 4 java junit spring dependency-injection 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

此服务将连接到REST端点到将部署的其他应用程序(由我开发).这就是我想在application.properties文件(-default,-qa,-dev)中自定义主机名的原因.

我的应用程序构建和工作正常.我通过创建调用此服务的控制器来测试它,并host使用application.properties中的正确属性填充字段.

当我尝试为此类编写测试时,会出现问题.当我尝试这种方法时:

@RunWith(SpringRunner.class)
public class MyServiceTest {

    @Autowired
    private MyService myService;

    @Test
    public void callEndpoint() {
        myService.callEndpoint();
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到例外:

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();
Run Code Online (Sandbox Code Playgroud)

但是host现场是null

Sas*_*ota 11

你也必须注释你的测试@SpringBootTest.

尝试:

@SpringBootTest
@RunWith(SpringRunner.class)
public class MyServiceTest {

    @Autowired
    private MyService myService;

    @Test
    public void callEndpoint() {
        myService.callEndpoint();
    }
}
Run Code Online (Sandbox Code Playgroud)