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.
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);
}
}