Issue
I have a bit of code I'd like to run in every @BeforeEach of all my integration tests files. Basically the code I need to add is the following :
@MockBean
RequestInterceptor interceptor; // I NEED THIS
@BeforeEach
public void initTest() throws Exception {
Mockito.when(interceptor.preHandle(any(), any(), any())).thenReturn(true); // AND THIS
}
Is there a way to avoid duplicating this part in every files ? Maybe I can create a test configuration file and use an annotation in my test files. As I am very new to java spring boot I would appreciate some help. Thanks.
Solution
You can create super class e.g. BaseTest and move this code there. And then every your test should just extend BaseTest. Even more you can set all Annotation in this class. E.g.:
@AutoConfigureMockMvc
@MockitoSettings(strictness = Strictness.STRICT_STUBS)
@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
@ActiveProfiles("test")
@SpringBootTest
public class BaseTest {
@MockBean
RequestInterceptor interceptor; // I NEED THIS
@BeforeEach
public void initTest() throws Exception {
Mockito.when(interceptor.preHandle(any(), any(), any())).thenReturn(true); // AND THIS
}
}
And then all your tests:
class MeasurementsServiceTest extends BaseTest {
//test methods here
}
Answered By - Viktar Patotski