如何在@SpringBootTest中创建可重用的@MockBean定义?
我有一个@SpringBootTest类,它有一个相当复杂的模拟定义设置,带有模拟的返回值。
问题:我可以将@MockBean设置外部化到一个自己的类中,以便我可以在多个类中重用模拟配置(旁注:我不是在这里寻找继承!)。
@SpringBootTest
public class ServiceTest extends DefaultTest {
@Autowired
private ServiceController controller;
@MockBean
private Service1 s1;
@MockBean
private Service2 s2;
@MockBean
private Service3 s3;
//assume more complex mock definitions
@BeforeEach
public void mock() {
when(s1.invoke()).thenReturn(result1);
when(s2.invoke()).thenReturn(result2);
when(s3.invoke()).thenReturn(result3);
}
@Test
public void test() {
//...
}
}
我想相互独立地加载模拟,而不是全局加载我的所有测试。
回答
不是您所要求的直接内容,而是一种可能性是不使用@MockBean而是将您的可重用模拟定义为@Primary @Bean多个@TestConfigurations 中的 s ,您可以@Import在测试中选择性地使用它:
@TestConfiguration
public class MockService1 {
@Bean
@Primary
public Service1 service1Mock() {
Service1 s1 = Mockito.mock(Service1.class);
when(s1.invoke()).thenReturn("result1");
return s1;
}
}
有一篇关于这种方法的好文章:Building Reusable Mock Modules with Spring Boot。
THE END
二维码