Let's get started with a Microservice Architecture with Spring Cloud:
Testing Spring MVC HandlerInterceptor
Last updated: July 11, 2026
1. Overview
A HandlerInterceptor in Spring MVC lets us intercept requests before and after controller execution. It’s useful for cross-cutting concerns like logging, authentication, or feature flags.
Testing Spring MVC HandlerInterceptor can be tricky because they’re wired into the request lifecycle. In this article, we’ll explore how to test one using @WebMvcTest and MockMvc, ensuring our interceptor logic works correctly without starting the full application.
2. The HandlerInterceptor Interface
A HandlerInterceptor allows us to execute logic before and after a controller handles a request. It operates within the Spring MVC layer, giving it access to handler metadata.
Spring MVC’s HandlerInterceptor interface defines three lifecycle methods:
- preHandle() – runs before the controller method executes
- postHandle() – runs after the controller completes but before generating the view
- afterCompletion() – runs after the entire request finishes, regardless of exceptions
3. Application Setup
Let’s consider an order processing application that calculates delivery charges. We want to roll out a new pricing algorithm gradually without redeploying the application. To achieve this, let’s configure a rollout percentage that determines how many requests use the new calculation (v2), while the rest fall back to the original (v1). We’ll use a HandlerInterceptor to make the routing decision before the controller executes, keeping it free of feature flag logic.
Let’s start by defining the FeatureFlagService interface. This represents an external service that provides the current rollout percentage:
public interface FeatureFlagService {
int rolloutPercentage();
}
The implementation details aren’t relevant here, hence we’ll mock these in our tests.
3.1. The Interceptor
Next, let’s create the DeliveryChargeInterceptor. It queries the rollout percentage, generates a random value, and routes to v2 when the random value falls below the rollout threshold:
public class DeliveryChargeInterceptor implements HandlerInterceptor {
static final String USE_V2_ATTRIBUTE = "useV2";
private final FeatureFlagService featureFlagService;
private final SecureRandom random = new SecureRandom();
private final Logger logger = LoggerFactory.getLogger(
DeliveryChargeInterceptor.class
);
public DeliveryChargeInterceptor(FeatureFlagService featureFlagService) {
this.featureFlagService = featureFlagService;
}
@Override
public boolean preHandle(
HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
int rollout = featureFlagService.rolloutPercentage();
boolean useV2 = rollout > 0 && random.nextInt(100) < rollout;
request.setAttribute(USE_V2_ATTRIBUTE, useV2);
logger.info(
"Delivery charge feature: rollout={}%, useV2={}",
rollout,
useV2
);
}
return true;
}
}
The handler instanceof HandlerMethod check ensures our logic only applies to controller methods, skipping static resource requests. Also, we should note that the interceptor doesn’t execute business logic. It simply makes a routing decision and passes it along via a request attribute.
3.2. The Controller
Next, Let’s create the controller that reads the attribute and delegates to the appropriate version:
@RestController
public class DeliveryChargesController {
private final DeliveryChargeService deliveryChargeService;
public DeliveryChargesController(DeliveryChargeService deliveryChargeService) {
this.deliveryChargeService = deliveryChargeService;
}
@PostMapping("/delivery-charges/calculate")
public double calculate(
@RequestParam String postcode,
HttpServletRequest request) {
Boolean useV2 = (Boolean) request.getAttribute(
DeliveryChargeInterceptor.USE_V2_ATTRIBUTE
);
if (Boolean.TRUE.equals(useV2)) {
return deliveryChargeService.calculateV2(postcode);
}
return deliveryChargeService.calculateV1(postcode);
}
}
3.3. Registering the Interceptor
Finally, let’s register the interceptor through WebMvcConfigurer and scope it to the delivery charges path:
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
private final FeatureFlagService featureFlagService;
public WebMvcConfig(FeatureFlagService featureFlagService) {
this.featureFlagService = featureFlagService;
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new DeliveryChargeInterceptor(featureFlagService))
.addPathPatterns("/delivery-charges/**");
}
}
The addPathPatterns() method ensures that only requests matching this path trigger the interceptor. All other endpoints remain unaffected.
4. Testing the Spring MVC HandlerInterceptor
Now, let’s verify the interceptor behavior using @WebMvcTest. This annotation loads only the web layer without starting the full application context. It includes controllers, interceptors, and their configuration. We’ll use @MockBean to provide mock implementations of our service interfaces:
@WebMvcTest(controllers = DeliveryChargesController.class)
class DeliveryChargeInterceptorIntegrationTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private DeliveryChargeService deliveryChargeService;
@MockBean
private FeatureFlagService featureFlagService;
}
It’s worth noting that @WebMvcTest automatically picks up any WebMvcConfigurer beans in the application context. Since our WebMvcConfig registers the interceptor, it becomes active during the test. This means we can test the full request flow from the interceptor through the controller without any additional configuration.
Let’s first verify that all requests use v1 when rollout is zero:
@Test
void givenZeroRollout_whenCalculateDeliveryCharge_thenV1IsUsed() throws Exception {
when(featureFlagService.rolloutPercentage()).thenReturn(0);
when(deliveryChargeService.calculateV1("SW1A")).thenReturn(5.0);
mockMvc.perform(post("/delivery-charges/calculate").param("postcode", "SW1A"))
.andExpect(status().isOk())
.andExpect(content().string("5.0"));
}
With a rollout of zero, the random check in the interceptor always evaluates to false. As a result, the controller consistently calls calculateV1().
Next, let’s confirm that all requests use v2 when rollout is 100%:
@Test
void givenFullRollout_whenCalculateDeliveryCharge_thenV2IsUsed() throws Exception {
when(featureFlagService.rolloutPercentage()).thenReturn(100);
when(deliveryChargeService.calculateV2("SW1A")).thenReturn(3.5);
mockMvc.perform(post("/delivery-charges/calculate").param("postcode", "SW1A"))
.andExpect(status().isOk())
.andExpect(content().string("3.5"));
}
At 100% rollout, the random value is always less than the threshold. Therefore, every request routes to calculateV2().
Finally, let’s verify that a 50% rollout produces a mix of both versions. We send 20 requests and assert that both v1 and v2 receive traffic:
@Test
void givenPartialRollout_whenCalculateDeliveryCharge_thenBothVersionsAreUsed() throws Exception {
when(featureFlagService.rolloutPercentage()).thenReturn(50);
when(deliveryChargeService.calculateV1("SW1A")).thenReturn(5.0);
when(deliveryChargeService.calculateV2("SW1A")).thenReturn(3.5);
int v1Count = 0;
int v2Count = 0;
for (int i = 0; i < 20; i++) {
String response = mockMvc.perform(
post("/delivery-charges/calculate")
.param("postcode", "SW1A")
)
.andExpect(status().isOk())
.andReturn()
.getResponse()
.getContentAsString();
if ("5.0".equals(response)) {
v1Count++;
} else if ("3.5".equals(response)) {
v2Count++;
}
}
assertThat(v1Count).isGreaterThan(0);
assertThat(v2Count).isGreaterThan(0);
}
This test proves that the interceptor distributes traffic between both versions based on the configured percentage.
5. Conclusion
In this article, we explored how to test a Spring MVC HandlerInterceptor using @WebMvcTest and MockMvc. This approach is helpful because @WebMvcTest loads only the web layer, making tests fast. It automatically picks up interceptors registered through WebMvcConfigurer, so we can verify the complete request flow without starting the full application context.
However, @WebMvcTest only verifies the web layer in isolation, so integration issues with services or repositories won’t surface here. For scenarios that require the complete application context, we can use @SpringBootTest with MockMvc instead. Additionally, for simple interceptor logic that doesn’t depend on Spring’s request handling, a unit test using a MockHttpServletRequest provides even faster feedback.
As always, the source code for this article is available over on GitHub.

















