【问题标题】:How to do a BeforeEach on all of my integration test files如何对我的所有集成测试文件执行 BeforeEach
【发布时间】:2020-12-31 22:08:25
【问题描述】:

我想在所有集成测试文件的每个 @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 很陌生,我将不胜感激。谢谢。

【问题讨论】:

  • 好吧,如果我正确理解您的问题,您可以创建一个具有 BeforeEach 方法的父基类,然后在所有其他基类上继承该类...
  • 您还可以使用 JUnit5 的扩展或 Junit 的 Runners JUnit 5 guide

标签: java spring spring-boot junit integration-testing


【解决方案1】:

您可以创建超类,例如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
}

【讨论】:

  • 我不得不重命名 initTest 方法,否则它会被测试文件中存在的 initTest 覆盖,否则它可以正常工作,谢谢!
【解决方案2】:

您可以创建一个具有 BeforeEach 方法的父基类,然后在所有其他基类上继承该类

public class BaseTestClass {

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

public class InheritsFromBase extends BaseTestClass {

// here goes test code
   
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多