这里有什么区别 - @Autowired 和 @MockBean

Ven*_*kat -1 junit spring-test mockito spring-boot spring-boot-test

我正在为 Spring Boot 项目中的服务类编写单元测试。当我自动装配正在测试的类时,测试可以正确运行,而当我使用 @MockBean 而不是 @Autowire 时,测试会失败。

@SpringBootTest
class SignupServiceTest {

  @Autowired SignupService signupService;

  @MockBean DSService dsService;

  @MockBean SignupHelper signupHelper;

  @MockBean SessionHelper sessionHelper;

  @MockBean CommonService commonService;
Run Code Online (Sandbox Code Playgroud)

有人可以帮我解决差异以及 @MockBean 失败的原因吗?还有一种方法可以在mockito中模拟自动装配类(当前类)的方法。

dan*_*niu 5

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

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

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