How to do a BeforeEach on all of my integration test files

Viewed 1119

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.

2 Answers

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
}

Well you can make a parent base class that would have the BeforeEach method and then just inherit that class on all of the other ones

public class BaseTestClass {

    @BeforeEach
    public void setUp(){
        System.out.println("Base Test Class");
    }
}

public class InheritsFromBase extends BaseTestClass {

// here goes test code
   
}
Related