Spring 启动测试:如何只启动上下文 1 次?

Spring boot Tests: how to up context only 1 time?

我只想对所有测试使用 1 个上下文。比起,我继承了 AbstractTest:

的所有测试 类
@SpringBootTest
public abstract class AbstractTest {
}

我预计上下文只会在一段时间内启动,但它适用于每个包。我有 5 个包裹,& context up 5 次。

如何仅启动上下文 1 次并保存包结构?

更新:测试示例:

@Test
void create() throws Exception {
    Car car = entityGenerator.createCar(profile.getId());
    String content = asJson(car);
    log.info(content);
    result = mockMvc.perform(
            post("/v1/car/add")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(content)
    )
            .andDo(print())
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.id").isNumber())
            .andExpect(jsonPath("$.profileId").value(car.getProfileId()))
            .andReturn();

    assertEquals(MediaType.APPLICATION_JSON_VALUE, result.getResponse().getContentType());
}

Spring 测试使用 Context Caching mechanism 在上下文配置匹配的情况下重用已经启动的上下文。所以默认情况下,你应该可以使用一个摘要 class 或者只用 @SpringBootTest 注释你的测试。测试或生产代码所在的包应该无关紧要。

然而,在某些情况下,如果您更改上下文配置的某些内容,Spring Test 将创建一个新的上下文,例如使用 @MockBean 或设置活动配置文件。

查看 official documentation,您可以找到配置参数列表 Spring 测试用于识别上下文。如果这些参数之一在整个测试过程中发生变化,您将创建一个新的上下文。

还要确保您的测试是在同一上下文中执行的,并且您没有使用 Maven Surefire 插件的任何 forkMode