MockBean存根无效

时间:2018-11-23 07:36:31

标签: spring spring-boot testing mocking mockito

我有一个配置类,其中有一些MockBean代替了上下文中的实际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

1 个答案:

答案 0 :(得分:1)

是的,应该在各自的测试用例中执行存根(除非您有一个共享存根方案的测试类,但是所有这些都归于偏好)。

但是,对于创建@MockBeans,您需要使用@SpringBootTest才能用模拟代替实际的bean。可以像下面的示例一样简单地完成此操作:

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

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

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

}
相关问题