Is it possible to externalize @MockBean
definitions, and combine them with composition instead of inheritance?
Because I find myself often repeating mock definitions, and I would rather be able to load/inject them and define them outside of the test class.
Example:
@SpringBootTest
public class Service1Test {
@MockBean
private Service1 service1;
@BeforeEach
public void mock() {
when(service1.call()).thenReturn(result1);
}
}
@SpringBootTest
public class Service2Test {
@MockBean
private Service2 service2;
@BeforeEach
public void mock() {
when(service2.call()).thenReturn(result2);
}
}
@SpringBootTest
public class Service3Test {
@MockBean
private Service1 service1;
@MockBean
private Service2 service2;
@BeforeEach
public void mock() {
when(service1.call()).thenReturn(result1);
when(service2.call()).thenReturn(result2);
}
}
I would like to externalize the mocks somehow, so I could just load them. Pseudocode as follows:
public class MockService1 {
@MockBean
private Service1 service1;
@BeforeEach
public void mock() {
when(service1.call()).thenReturn(result1);
}
}
@SpringBootTest
@Import({MockService1.class, MockService2.class})
public class Service3Test {
}