问题描述
我在 Spring Boot 项目中为我们的服务类编写单元测试。当我自动装配正在测试的类时测试正常运行的地方,当我使用 @Autowire 的 @MockBean 时它失败了。
@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
等控制并使用 verify
等进行检查。它们的特别之处在于它们被注入到上下文中的其他 bean 中(例如,当您调用 Mockito.initAnnotations(this)
时)。