首页 > 解决方案 > Mockito @SpyBean 注解与 SpringRunner 冲突

问题描述

我目前正在尝试创建存储库的部分模拟,但是每当我尝试使用 SpyBean 注释 JDBC 存储库时都会遇到问题。

@RunsWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = ServiceApplication.class)
@ActiveProfiles("unit-test")
public abstract class TestBase {

    @SpyBean
    protected JdbcRepository jdbcRepository;

    @Before
    public void baseSetUp() throws Exception {
        MockitoAnnotations.initMocks(this);

        this.testContextManager = new TestContextManager(getClass());
        this.testContextManager.prepareTestInstance(this);

        this.classLoader = getClass().getClassLoader();
        ...
    }

当我运行应用程序时,我收到以下消息:

org.springframework.beans.factory.BeanCreationException:无法注入字段:受保护的 com.sample.app.JdbcRepository 不能有现有值

但是,我找到了一些避免错误的方法:

简而言之,我不确定为什么我的测试会抛出 BeanCreationException。类成员上方的@SpyBean注解不是使用spy beans的正确方法吗?

标签: javaspringjunitmockingmockito

解决方案


推荐阅读