【问题标题】:What is difference here - @Autowired and @MockBean这里有什么区别 - @Autowired 和 @MockBean
【发布时间】:2021-06-26 11:02:56
【问题描述】:

我正在为 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-boot junit mockito spring-test spring-boot-test


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2011-11-25
      • 1970-01-01
      • 2017-10-15
      • 1970-01-01
      • 2019-05-06
      • 2021-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多