首页 > 解决方案 > 如何在不加载整个上下文的情况下加载单个 bean 以在 Spring Boot 中进行测试?

问题描述

我有一个依赖于 bean B 的 A 类(非常简单的 bean,只是一个要调用的时钟)。我想对A类进行单元测试,如何加载这个bean?@SpringBootTest 加载整个上下文。

标签: javaspringspring-boot

解决方案


您应该使用两个注解的组合:

@ExtendWith(SpringExtension.class)
@Import(
        value = {
                SomeSpringBean.class
        }
)

whereto@Import的值你可以在没有 spring-context 构建的情况下放置你的非模拟 bean。您可以通过@Import 任何spring bean(带有@Configuration 或@Component 等的类)在此测试中模拟另一个bean 使用@MockBean 注释。用法如下所示:

@ExtendWith(SpringExtension.class)
@Import(
        value = {
                SomeSpringBean.class
        }
)
class SomeSpringTest {

    @MockBean
    private MockedBean mock;

    @Autowired
    private SomeSpringBean bean;

...
}

在 javadoc 中查看更多信息:

指示要导入的一个或多个组件类——通常是 @Configuration 类。提供与 Spring XML 中的元素等效的功能。允许导入@Configuration 类、ImportSelector 和 ImportBeanDefinitionRegistrar 实现,以及常规组件类(从 4.2 开始;类似于 AnnotationConfigApplicationContext.register)。在导入的@Configuration 类中声明的@Bean 定义应该使用@Autowired 注入来访问。bean 本身可以自动装配,或者声明 bean 的配置类实例可以自动装配。后一种方法允许在 @Configuration 类方法之间进行显式的、IDE 友好的导航。


推荐阅读