首页 > 解决方案 > 使用配置文件时 SpringBoot 测试无法自动装配服务

问题描述

我试图通过以下方式为我的命令行应用程序运行 SpringBoot 测试

https://www.baeldung.com/spring-junit-prevent-runner-beans-testing-execution

如果我在 Test 类中没有 Autowried,它就可以工作

如果我使用带有 ActiveProfiles 注释的 Autowired 注释,则无法加载服务组件类。

有人可以给我一个提示如何解决它吗?

标签: spring-boot-test

解决方案


为了解决问题,我们可以在执行主进程之前检查活动配置文件

    @Override
    public void run(String... args) throws Exception {
        if (!Stream.of(env.getActiveProfiles()).collect(Collectors.toCollection(ArrayList::new)).contains("test")) {
            myMainProcess();
        }

    }

推荐阅读