Search code examples
javaspringspring-boot-test

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


I want to use only 1 context for all tests. Than, I inherit all test classes of AbstractTest:

@SpringBootTest
public abstract class AbstractTest {
}

I expect that context will be up only time, but it up for every package. I have 5 packages, & context up 5 times.

enter image description here

How to up context only 1 time & to save packages structure?

UPD: test example:

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

Solution

  • Spring Test uses a Context Caching mechanism to reuse already started contexts if the context configuration matches. So by default, you should be fine with having one abstract class or just by annotating your tests with @SpringBootTest. The package where the test or production code is in, shouldn't matter.

    There are however scenarios where Spring Test will create a new context if you change something for the context configuration e.g. use @MockBean or set the active profile.

    Take a look at the official documentation and you can find the list of configuration parameters Spring Test uses to identify a context. If one of these parameters changes throughout your tests, you'll get a new context created.

    Also ensure that your tests are executed within the same context and you are not using any forkMode of the Maven Surefire plugin.