我有一个 @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
s 在多个 @TestConfiguration
您可以选择性地@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 .
关于java - 如何在@SpringBootTest 中创建可重用的@MockBean 定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67054014/