eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

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.

Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)
guest
0 Comments
Oldest
Newest
Inline Feedbacks
View all comments