spring-boot - 这里有什么区别 - @Autowired 和 @MockBean
问题描述
我在 Spring Boot 项目中为我们的服务类编写单元测试。当我自动装配正在测试的类时,测试在哪里正常运行,而当我使用@MockBean insead of @Autowire 时它会失败。
@SpringBootTest
class SignupServiceTest {
@Autowired SignupService signupService;
@MockBean DSService dsService;
@MockBean SignupHelper signupHelper;
@MockBean SessionHelper sessionHelper;
@MockBean CommonService commonService;
可以帮助我解决差异以及@MockBean 失败的原因。还有一种方法可以在 mockito 中模拟自动装配类(当前类)的方法。
解决方案
@SpringBootTest 是一个实际启动 Spring 容器以及应用程序 bean 的测试。
测试中的@Autowired 字段的行为与普通 Spring-Beans 中的行为一样;它们被注入应用程序中配置的实际bean(xml、@Configuration 中的@Bean 或@Component/@Service)。
@MockBean 创建一个模拟,它们的行为类似于普通模拟,您可以使用when/then
etc 控制并检查verify
等。它们的特殊之处在于它们被注入到上下文中的其他 bean 中(例如,当您调用 时Mockito.initAnnotations(this)
)。
推荐阅读
- php - Laravel 8:尝试在 int 上读取属性“user_id”
- python - 如何在 pdf 中找到空白页?
- c# - 从位置将多行插入文件而不覆盖先前插入的行
- hyperlink - 修改多个超链接
- javascript - 在字符串“welcome”之前或之后不检查任何内容
- python - 仅将一个数据帧的日期时间索引保留在另一个数据帧中
- mysql - 在 2 个 GROUP_CONCAT 的列之间查找不常见的项目
- flutter - 使用 mainAxisAlignment.spaceBetween 后减少列小部件中的一些空格
- javascript - 如何正确计算参数内的变量
- database - 错误:FUNCTION function_name,已编译错误:检查编译器日志