Yeda AI Tips · #075

Español

Slice Tests, Not a Full Boot

Stop booting your whole app for one controller test. In Spring, a full @SpringBootTest wires every layer — web, services, data, config — which is exactly right for cross-layer behavior and exactly wrong as a default habit. Spring Boot ships purpose-built slice tests that load only the layer under test, and the difference compounds across every test class and every CI run.

What a slice test actually loads

Each @…Test slice annotation does two things: it restricts component scanning to the beans relevant to that layer, and it imports only a small set of auto-configurations instead of all of them.

Rules of thumb

You are testing…UseNot
A controller's routing, status codes, validation@WebMvcTest(MyController.class)@SpringBootTest
A repository query or entity mapping@DataJpaTest@SpringBootTest
JSON serialization of a DTO@JsonTesta controller test
An outbound REST client@RestClientTesthitting the real API
Real cross-layer behavior (wiring, transactions across layers, security end-to-end)@SpringBootTeststacking mocks in a slice

One constraint worth knowing: you cannot combine multiple @…Test slice annotations on one class. Pick the slice that matches the layer, and pull in extras with the matching @AutoConfigure… annotation if needed.

A controller slice in practice

@WebMvcTest(UserVehicleController.class)
class UserVehicleControllerTests {

    @Autowired
    private MockMvc mvc;

    @MockitoBean
    private UserVehicleService userVehicleService;

    @Test
    void returnsVehicleDetails() throws Exception {
        given(userVehicleService.getVehicleDetails("sboot"))
                .willReturn(new VehicleDetails("Honda", "Civic"));
        mvc.perform(get("/sboot/vehicle"))
                .andExpect(status().isOk())
                .andExpect(content().string("Honda Civic"));
    }
}

No datasource, no service layer, no full context — just the web layer and one stub.

Why this matters for AI-assisted coding

An AI assistant learns your codebase's habits by example. If every existing test is a full-boot @SpringBootTest, the assistant will reach for the heaviest tool for every new test it writes — and your feedback loop degrades one generated file at a time. Seed the repo with slice tests, and state the convention explicitly in your project instructions: "controller tests use @WebMvcTest, repository tests use @DataJpaTest, @SpringBootTest is reserved for cross-layer behavior." Generated tests then follow the fast path by default.

Power-user: exploit context caching

Spring's test framework caches application contexts between tests — a context is built once per unique configuration and reused, with a default cache cap of 32 contexts (LRU-evicted; tune with -Dspring.test.context.cache.maxSize). Two habits maximize hits:

Resources

Building an AI feature? Yeda AI designs, audits, and ships production LLM systems.

Talk to us · Read the blog