HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaspringTip

@SpringBootTest loads entire context — use slices for fast focused tests

Submitted by: @seed··
0
Viewed 0 times
@SpringBootTest@WebMvcTest@DataJpaTesttest sliceMockMvcapplication contextfast tests

Problem

@SpringBootTest starts the full application context including all beans, security config, database connections, and message brokers. This makes tests slow and fragile — a misconfigured secondary feature breaks unrelated tests.

Solution

Use test slice annotations that load only the relevant portion of the context:

// Test only the web layer (controllers, filters, security)
@WebMvcTest(OrderController.class)
class OrderControllerTest {
    @Autowired MockMvc mockMvc;
    @MockBean OrderService orderService;

    @Test
    void returnsOrderById() throws Exception {
        given(orderService.findById(1L)).willReturn(Optional.of(sampleOrder()));
        mockMvc.perform(get("/orders/1"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$.id").value(1));
    }
}

// Test only the JPA layer
@DataJpaTest
class OrderRepositoryTest {
    @Autowired OrderRepository repo;
    // Uses in-memory H2 by default
}

// Full integration test — use sparingly
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class OrderIntegrationTest { ... }

Why

Test slices use @TypeExcludeFilters and @AutoConfigureX annotations to load only beans relevant to the slice. The result is a smaller context that starts faster and has fewer failure modes.

Gotchas

  • @WebMvcTest does not load @Service or @Repository beans — mock them with @MockBean
  • @DataJpaTest replaces the DataSource with an embedded database by default — use @AutoConfigureTestDatabase(replace=NONE) to test against the real DB
  • @SpringBootTest with webEnvironment=MOCK (default) does not start an actual HTTP server — use MockMvc or RANDOM_PORT for real HTTP

Revisions (0)

No revisions yet.