在 spring 单元测试期间避免不必要的 @Component 构造

Avoid unnecessary @Component construction during spring unit test

假设定义了两个 @Component,如下所示:

@Component
public class UnderTesting {
}
@Component
public class Irrelevant {
}

单元测试是这样的:

@SpringBootTest
public Test_UnderTesting {
    @Autowired
    private UnderTesting foo;

    @Test
    public void testSomething() {
    }
}

当 运行 这个带有 mvn test 的测试用例时,spring 将构建组件 Irrelevant,即使它完全不相关。

在我的例子中,组件 Irrelevant 无法构建 由于单元测试环境中复杂的依赖关系不可用。

我的问题是:如何避免在单元测试期间构建 Irrelevant(和其他不必要的组件)?

我是 spring 引导的新手,所以我可能走错了方向,欢迎任何建议。

我们可以延迟加载组件,即在@Component 之上使用@Lazy 注解

有关详细信息,请参阅此 link:https://www.baeldung.com/spring-lazy-annotation

需要了解的一件事是,一旦使用 @SpringBootTest,它就不再是单元测试了。使用该注释的要点是,您的应用程序上下文开始时尽可能类似于生产使用。

您可以专门为此测试用例定义一个单独的配置 class,您只创建一个 class UnderTesting 的 bean,如下所示:

@SpringBootTest(classes = {TestConfiguration.class})

在 TestConfiguration.class 中,您可以像这样创建一个 bean 工厂方法:

public UnderTesting underTesting() {
    return new UnderTesting();
}

但我更愿意看看您是否可以将此测试编写为真正的单元测试(如果这是您想要的),而不使用任何 Spring 启动功能,并模拟任何依赖项。

创建一个 test 配置文件,以便在 运行 测试时使用,并使用 @Profile("!test") 注释 Irrelevant class 怎么样?