Excluding Filters When using WebMvcTest

Featured image for sharing metadata for article

As noted in my article Shift Your Testing Left with Spring Boot Controllers, the aim of writing WebMvcTests is to verify that Spring annotations are set on the class, and that it actually responds as a controller.

Although it's an integration test, we should try and keep our test slice as thin as possible.

For instance, we may have Filters running in the background, which may be requiring that we have a correlation-id sent in each request, which is adding additional complexity in our requests.

Let's say that our test class is being set up with the following annotation:

import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;

@WebMvcTest(MetadataController.class)

We'd now be able to tweak this to:

import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;

@WebMvcTest(
    value = MetadataController.class,
    excludeFilters =
        @ComponentScan.Filter(
            type = FilterType.ASSIGNABLE_TYPE,
            classes = CorrelationIdFilter.class))

And our tests would no longer be using the CorrelationIdFilter.

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #java #spring #spring-boot #testing #tdd.

Also on:

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.