首页 > 解决方案 > MockBean 存根无效

问题描述

我有一个配置类,其中一些 MockBeans 替换了上下文中的实际 bean 以进行测试。

@Configuration
public class MyTestConfig {
    @MockBean
    private MyService myService;
}

我在测试中使用这些模拟:

@Import({ MyTestConfig .class })
public class MyTest {
    @Autowired
    private MyService myService;

    @Test
    public void aTest() {
        ...
    }
}

首先的想法是在这个MyTestConfig配置类中添加存根,以便为所有测试预先制作模拟,所以我在一个@PostConstruct方法中做了它,它工作得很好 - 测试中的模拟确实返回了预期值:

@PostConstruct
public void init() {
    when(myService.foo("say hello")).thenReturn("Hello world");
}

但事实证明,构建一个适合所有测试的预制模拟可能很棘手,因此我们决定将存根转移到测试中。

@Test
public void aTest() {
    when(myService.foo("say hello")).thenReturn("Hello world");
}

这不起作用 - 存根方法返回null。我们想将 MockBeans 留在配置类中,但在测试中对它们进行存根,那么关于为什么存根无效的任何建议?

Spring Boot 2.0.5,Mockito 2.22.0

标签: springspring-boottestingmockingmockito

解决方案


是的,应该在各自的测试用例中执行存根(除非您有一个共享存根场景的测试类,但这一切都归结为偏好)。

但是,对于创建@MockBeans,您需要使用 a@SpringBootTest来将实际的 bean 替换为模拟。这可以像这个例子一样简单地完成:

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTest {

    @Autowired
    private MyTestClass testClass;
    @MockBean
    private MyService service;

    @Test
    public void myTest() {
      // testing....
  }

}

推荐阅读