Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Customize WebTestClient to add a default header

I have developed a Spring Boot app in version 2.7.x. For the integration tests i am trying to customize the WebTestClient to add a default header.

I have already tried this but the header is not added in the request:

@AutoConfigureWebTestClient
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class TestClass1{

    @Autowired
    private WebTestClient webTestClient;

    @Test
    public void test1() throws Exception {
        webTestClient.get()
                .uri("/foobar/")
                .exchange()
                .expectStatus().isOk()
                .expectBody(JsonArray.class);
   }
}

Configuration class:

@TestConfiguration
public class WebTestClientConfig {

    @Bean
    public WebTestClient client() {
        return WebTestClient.bindToServer()
                .responseTimeout(Duration.ofMinutes(2))
                .defaultHeader(API_KEY_HEADER, API_KEY_VALUE)
                .exchangeStrategies(ExchangeStrategies.withDefaults())
                .build();
    }
}

Update:

I also tried to use the WebTestClientBuilderCustomizer in the 'WebTestClientConfig' class and removed the 'client()' method but the problem still exists. See this example:

@TestConfiguration
public class WebTestClientConfig {

    @Bean
    public WebTestClientBuilderCustomizer webTestClientBuilderCustomizer() {
        return (builder) -> builder.defaultHeader(API_KEY_HEADER, API_KEY_VALUE);
    }

}

Any ideas on how to archive my goal? Thx.

like image 818
Ben Avatar asked Jun 10 '26 00:06

Ben


1 Answers

With the help of @samabcde I changed my code to this solution:

Test class:

@AutoConfigureWebTestClient
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@Import(WebTestClientConfig.class) // <---- !added!
public class TestClass1{

    @Autowired
    private WebTestClient webTestClient;

    @Test
    public void test1() throws Exception {
        webTestClient.get()
                .uri("/foobar/")
                .exchange()
                .expectStatus().isOk()
                .expectBody(JsonArray.class);
   }
}

Configuration class:

@TestConfiguration
public class WebTestClientConfig {

    @Bean
    public WebTestClientBuilderCustomizer webTestClientBuilderCustomizer() {
        return (builder) -> builder.defaultHeader(API_KEY_HEADER, API_KEY_VALUE);
    }

}
like image 127
Ben Avatar answered Jun 11 '26 17:06

Ben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!