春季启动测试:如何仅一次上下文一次?

时间:2020-07-13 12:06:32

标签: java spring spring-boot-test

我只想对所有测试使用1个上下文。然后,我继承了AbstractTest的所有测试类:

@SpringBootTest
public abstract class AbstractTest {
}

我希望上下文只会出现一次,但是对于每个程序包而言都是如此。我有5个程序包,上下文最多5次。

enter image description here

如何仅一次上下文关联并保存包结构?

UPD:测试示例:

@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());
}

1 个答案:

答案 0 :(得分:1)

如果上下文配置匹配,Spring Test使用Context Caching mechanism重用已经启动的上下文。因此,默认情况下,您最好拥有一个抽象类,或者仅使用@SpringBootTest注释测试。测试或生产代码所在的程序包无关紧要。

但是在某些情况下,如果您更改了上下文配置,例如,Spring Test将创建新的上下文。使用@MockBean或设置有效的个人资料。

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

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