如何对我所有的集成测试文件执行 BeforeEach
How to do a BeforeEach on all of my integration test files
我有一些代码想要 运行 在我所有集成测试文件的每个 @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 引导的新手,因此我希望得到一些帮助。谢谢
您可以创建超级 class 例如BaseTest 并将此代码移到那里。然后你的每一个测试都应该扩展 BaseTest。您甚至可以在此 class 中设置所有 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
}
好吧,您可以创建一个具有 BeforeEach 方法的父基 class,然后在所有其他基
上继承 class
public class BaseTestClass {
@BeforeEach
public void setUp(){
System.out.println("Base Test Class");
}
}
public class InheritsFromBase extends BaseTestClass {
// here goes test code
}
我有一些代码想要 运行 在我所有集成测试文件的每个 @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 引导的新手,因此我希望得到一些帮助。谢谢
您可以创建超级 class 例如BaseTest 并将此代码移到那里。然后你的每一个测试都应该扩展 BaseTest。您甚至可以在此 class 中设置所有 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
}
好吧,您可以创建一个具有 BeforeEach 方法的父基 class,然后在所有其他基
上继承 classpublic class BaseTestClass {
@BeforeEach
public void setUp(){
System.out.println("Base Test Class");
}
}
public class InheritsFromBase extends BaseTestClass {
// here goes test code
}