首页 > 解决方案 > 如何对我的所有集成测试文件执行 BeforeEach

问题描述

我想在所有集成测试文件的每个 @BeforeEach 中运行一些代码。基本上我需要添加的代码如下:

@MockBean
RequestInterceptor interceptor; // I NEED THIS

@BeforeEach
public void initTest() throws Exception {
    Mockito.when(interceptor.preHandle(any(), any(), any())).thenReturn(true); // AND THIS
}

有没有办法避免在每个文件中重复这部分?也许我可以创建一个测试配置文件并在我的测试文件中使用注释。由于我对 java spring boot 很陌生,我将不胜感激。谢谢。

标签: javaspringspring-bootjunitintegration-testing

解决方案


您可以创建超类,例如 BaseTest 并将此代码移到那里。然后你的每一个测试都应该扩展 BaseTest。更多的你可以在这个类中设置所有的 Annotation。例如:

@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
    }
}

然后你所有的测试:

class MeasurementsServiceTest extends BaseTest {
//test methods here
}

推荐阅读