【问题标题】:mockito with spring boot mock bean in initialization return null初始化中带有 Spring Boot 模拟 bean 的模拟返回 null
【发布时间】:2020-11-05 09:06:18
【问题描述】:

我在 Spring Boot 项目中定义了一些 bean,BeanA:

@Component
public class BeanA {
    public String getName() {
        return "A";
    }
}

BeanB:

@Component
public class BeanB {
    @Autowired
    private BeanA beanA;

    private String name;

    @PostConstruct
    public void init() {
        this.name = beanA.getName();
    }

    public String getName() {
        return this.name;
    }

}

当我模拟 beanA.getName 时,它​​返回 null

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { MockitoTestApplication.class })
public class BeanTest {
  @Autowired
  private BeanB beanB;

  @MockBean
  private BeanA beanA;

  @Before
  public void mock() {
    MockitoAnnotations.initMocks(this);
    Mockito.doReturn("mockA").when(beanA).getName();
  }

  @Test
  public void testGetName() {
    System.out.println(beanB.getName()); // return null here
  }
}

我猜这里有一些 bean 加载优先级,根本原因是什么以及如何解决它?

【问题讨论】:

  • 您的模拟行为在 bean 已经构建之后被注册,因此 getName 已经被调用。重写你的getName 来做return beanA.getName(),它会返回你想要的。同时删除 MockitoAnntations.initMocks Spring Boot Test 支持为您处理的句柄。

标签: java spring-boot mockito


【解决方案1】:

首先你不需要使用MockitoAnnotations.initMocks(this); @MockBean 创建一个模拟并将 bean 添加到应用程序上下文(添加一个新的或替换现有的)。从技术上讲,这个模拟已经是“模拟驱动的”,所以你可以指定对它的期望等等。

现在代码的真正问题是您试图访问 @Before 方法中的 bean,该方法在技术上是在 spring 发挥其魔力之前调用的,它是 JUnit 框架的一部分。

对于像这个 Spring 测试库这样的案例,发明了侦听器的概念,它绑定到 Spring 应用程序上下文生命周期,而不是单元测试的生命周期。

所以从技术上讲,您可以从侦听器中调用Mockito.doReturn("mockA").when(beanA).getName(); TestExecutionListener#beforeTestMethod 来完成这项工作。

对于一般解释阅读this SO thread 和更深入的例子this article

【讨论】:

  • 如果我在 beforeTestMethod 中添加 Mock 逻辑,beanA 在 when() 中将为空
  • 你能分享一下代码吗?您是否使用了正确的合并模式? @TestExecutionListeners(value = {MyFilter.class}, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS)
  • 顺便说一句,澄清一下:你从@M.Deinum 得到的评论是完全正确的,所以除了评论之外,你还应该考虑这个答案。
猜你喜欢
  • 1970-01-01
  • 2019-07-28
  • 2018-10-17
  • 2019-11-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-24
  • 2022-01-11
  • 1970-01-01
相关资源
最近更新 更多