java - 如何在不加载整个上下文的情况下加载单个 bean 以在 Spring Boot 中进行测试?
问题描述
我有一个依赖于 bean B 的 A 类(非常简单的 bean,只是一个要调用的时钟)。我想对A类进行单元测试,如何加载这个bean?@SpringBootTest 加载整个上下文。
解决方案
您应该使用两个注解的组合:
@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 友好的导航。
推荐阅读
- python - 使用 selenium 和 beautifulsoup 进行网页抓取
- django - Django ORM:获取所有记录以及每条记录各自的最后一个日志
- android - 如何在计算器程序的数字字符串中以单个小数形式输入?
- python - Python:根据其他两列的值有条件地创建新列
- json - 执行自定义解组后解组剩余的 JSON
- javascript - 受控禁用按钮 Material UI - React JS
- pdf - 无法在 odoo-12 中上传文件大小为 1MB 或更大的 PDF 文件
- swift - NSTextField 的文本方向
- python - 内部函数上的 Python lru_cache 似乎不起作用
- vue.js - 如果 v-for 中带空格的数组的对象名