BBackend CourseLeroy Labs
0/0
Search the course

Slice tests with @WebMvcTest & security tests

Testing controllers without the whole app. MockMvc, @MockitoBean, testing 401/403/400 paths, method-security config in tests, and why Hostel's rate-limit filter is not a @Component.

● intermediateHostel-Web-App

The concept

@WebMvcTest starts only the web layer: controllers, @ControllerAdvice, filters, Jackson and security. It doesn’t start JPA, services or the DB. It’s fast and focused on the HTTP contract: status codes, JSON shape, validation and auth.

@WebMvcTest(controllers = BookingController.class)
@Import({MethodSecurityTestConfig.class, JacksonConfig.class})
class BookingControllerTest {
    @Autowired MockMvc mvc;
    @MockitoBean BookingService bookingService;        // Spring Boot 3.4+ replacement for @MockBean

    @Nested @DisplayName("POST /api/bookings")
    class Create {
        @Test void unauthenticated_returns401() throws Exception {
            mvc.perform(post("/api/bookings").contentType(JSON).content("{}"))
               .andExpect(status().isUnauthorized());
        }

        @Test @WithMockUser(roles = "MANAGER")
        void wrongRole_returns403() throws Exception {
            mvc.perform(post("/api/bookings").contentType(JSON).content(validBody()))
               .andExpect(status().isForbidden());
        }

        @Test @WithMockUser(roles = "STUDENT")
        void invalidSemester_returns400WithFieldError() throws Exception {
            mvc.perform(post("/api/bookings").contentType(JSON)
                    .content("""{"roomId":"%s","academicYear":"2026/2027","semester":"SUMMER"}""".formatted(UUID.randomUUID())))
               .andExpect(status().isBadRequest())
               .andExpect(jsonPath("$.code").value("VALIDATION_FAILED"))
               .andExpect(jsonPath("$.fieldErrors.semester").exists());
        }
    }
}

In your project

Hostel-Web-AppBookingControllerTest · MethodSecurityTestConfig · RateLimitingFilter (deliberately not @Component)
  • @WebMvcTest(controllers = BookingController.class) @Import({MethodSecurityTestConfig.class, JacksonConfig.class}).
  • @MockitoBean BookingService.
  • @Nested / @DisplayName groups covering 401, 403 and validation.

A subtle design choice: RateLimitingFilter is created with new inside SecurityConfig rather than being a @Component. @WebMvcTest automatically includes Filter beans, so a component-scanned rate limiter would start throttling controller tests.

Other slices

Annotation Loads Use
@WebMvcTest MVC + security Controllers
@DataJpaTest JPA, repositories (+ Testcontainers) Queries, mappings, constraints
@JsonTest Jackson DTO serialisation contracts
@RestClientTest RestClient / RestTemplate + mock server HTTP adapters (Paystack client)
@SpringBootTest Everything Integration (next lesson)
  • @WithMockUser / @WithUserDetails / custom @WithSecurityContext for authenticated tests.
  • jsonPath assertions pin down the API contract.
  • MockMvc vs WebTestClient vs RestAssured. All are fine; RestAssured is popular for full-stack API tests.
  • Spring REST Docs generates API documentation from passing tests.

Check yourself

1. What does @WebMvcTest NOT start?
2. Why is Hostel’s RateLimitingFilter not a @Component?