【发布时间】:2021-05-01 16:13:36
【问题描述】:
为了避免 Spring 上下文一次又一次地重新加载,我将 @MockBean 带注解的注入移到了父类中,类似这样。
@SpringBootTest
.......
public abstract BaseTest {
@MockBean
protected OneService oneService;
这为需要模拟OneService 的测试类提供服务。但是,对于我也想从BaseTest 扩展的测试,但通过@Autowired 注入真正的OneService 将不起作用,因为它将从BaseTest 继承模拟注入。
public AnotherTest extends BaseTest {
@Autowired
protected OneService oneService;
即使我使用了@Autowired 注释,oneService 字段也将是从BaseTest 继承的模拟实例。
有没有办法强制注入使用自动连线?
【问题讨论】:
-
基于对 Spring Boot Test 内部结构的快速浏览,我认为目前不可能实现这一目标。
DefinitionsParser似乎没有考虑到字段可能被子类覆盖:github.com/spring-projects/spring-boot/blob/master/… -
尝试构造函数注入,这种方式可能可以将 bean 从子级提供给父级,看看这种方法,可能会有所帮助。
-
谢谢。有没有我想做的选择?我正在考虑使用@ Qualifier,但这意味着我需要分别将 bean 初始化为带有限定符的模拟和实际 OneService。我正在努力让它发挥作用。我可能会在某个地方错过理解。 @MockBean 自动注入到上下文中,所以我无能为力,所以我只能用限定符更新 OneService 实现并更改所有使用它的地方?
标签: java spring-boot mockito integration-testing spring-test