首页 > 解决方案 > 这里有什么区别 - @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 中模拟自动装配类(当前类)的方法。

标签: spring-bootjunitmockitospring-testspring-boot-test

解决方案


@SpringBootTest 是一个实际启动 Spring 容器以及应用程序 bean 的测试。

测试中的@Autowired 字段的行为与普通 Spring-Beans 中的行为一样;它们被注入应用程序中配置的实际bean(xml、@Configuration 中的@Bean 或@Component/@Service)。

@MockBean 创建一个模拟,它们的行为类似于普通模拟,您可以使用when/thenetc 控制并检查verify等。它们的特殊之处在于它们被注入到上下文中的其他 bean 中(例如,当您调用 时Mockito.initAnnotations(this))。


推荐阅读