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

标签 java spring spring-boot junit dependency-injection

我正在 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)。

我的应用程序构建并运行良好。我通过创建调用此服务的 Controller 对其进行了测试,并使用 application.properties 中的正确属性填充 host 字段。

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

@RunWith(SpringRunner.class)
public class MyServiceTest {

    @Autowired
    private MyService myService;

    @Test
    public void callEndpoint() {
        myService.callEndpoint();
    }
}

我收到异常:

org.springframework.beans.factory.UnsatisfiedDependencyException:创建名称为“com.ge.bm.wip.comp.processor.service.MyServiceTest”的 bean 时出错:通过字段“myService”表达的不满足依赖关系;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用类型为“com.ge.bm.wip.comp.processor.service.MyService”的合格 bean:预计至少有 1 个 bean 有资格作为 Autowiring 候选。

还有一些嵌套异常。如果有帮助,我可以发布它们。 我想出于某种原因,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();
    }
}

关于java - 在 Spring Boot 中的 JUnit 测试中创建 bean 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45863347/

相关文章:

java - 谷歌应用程序引擎java后端_ah/start

java - Eclipse文本编辑器获取光标位置

java - Kryonet RMI,无法等待连接更新线程的响应

java - 通过 Spring Reactor 从 Future 创建 HotStream

java - 无法在Spring Boot中实现Drools KieSession持久化

java - Spring Security 中 Web 忽略和 Http 允许之间的区别?

java - Spring没有从systemd服务中看到环境变量

java - 使用来自另一个 ArrayList 的映射实例化 ArrayList

spring - 仅在没有其他服务的情况下为接口(interface)加载服务

java.io.IOException : invalid constant type: 19 at 5 异常