英文:
How to do a BeforeEach on all of my integration test files
问题
我有一段代码,我想在所有集成测试文件的每个@BeforeEach中运行它。基本上我需要添加的代码如下:
@MockBean
RequestInterceptor interceptor; // 我需要这部分
@BeforeEach
public void initTest() throws Exception {
Mockito.when(interceptor.preHandle(any(), any(), any())).thenReturn(true); // 还有这部分
}
有没有办法避免在每个文件中重复这部分代码?也许我可以创建一个测试配置文件,并在我的测试文件中使用一个注释。因为我对Java Spring Boot非常陌生,所以希望能得到一些帮助。谢谢。
英文:
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.
答案1
得分: 2
你可以创建一个超类,例如BaseTest,并将这段代码放在那里。然后每个测试只需要扩展BaseTest。甚至更多,你可以在这个类中设置所有的注解。例如:
@AutoConfigureMockMvc
@MockitoSettings(strictness = Strictness.STRICT_STUBS)
@ExtendWith(MockitoExtension.class)
@ExtendWith(SpringExtension.class)
@ActiveProfiles("test")
@SpringBootTest
public class BaseTest {
@MockBean
RequestInterceptor interceptor; // 我需要这个
@BeforeEach
public void initTest() throws Exception {
Mockito.when(interceptor.preHandle(any(), any(), any())).thenReturn(true); // 还有这个
}
}
然后你所有的测试可以这样写:
class MeasurementsServiceTest extends BaseTest {
// 这里是测试方法
}
英文:
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
}
答案2
得分: 1
您可以创建一个父基类,其中包含 `BeforeEach` 方法,然后在所有其他类中继承该类。
public class BaseTestClass {
@BeforeEach
public void setUp(){
System.out.println("Base Test Class");
}
}
public class InheritsFromBase extends BaseTestClass {
// 这里放置测试代码
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论