Unit testing WebClient has very low ROI. I would recommend looking at WireMock that provides very good API for testing web clients. Here are some examples

stubFor(get(url)
        .withHeader(HttpHeaders.ACCEPT, containing(MediaType.APPLICATION_JSON_VALUE))
        .willReturn(aResponse()
                .withStatus(200)
                .withBody("{}")
        )
);

StepVerifier.create(service.callApi())
        .expectNextCount(1)
        .verifyComplete();

You could easily test both positive and negative scenarios by providing different stubs

stubFor(get(url)
        .withHeader(HttpHeaders.ACCEPT, containing(MediaType.APPLICATION_JSON_VALUE))
        .willReturn(aResponse()
                .withStatus(500)
        )
);

In addition, you could test retry logic using Scenarios or even simulate timeouts using Delays.

To initialize it you could use @AutoConfigureWireMockprovided by org.springframework.cloud:spring-cloud-contract-wiremock or, as an alternative, you can add direct dependency to WireMock and initialize it explicitly.

Answer from Alex on Stack Overflow
🌐
Spring
docs.spring.io › spring-framework › reference › testing › webtestclient.html
WebTestClient :: Spring Framework
WebTestClient is an HTTP client designed for testing server applications. It wraps Spring’s WebClient and uses it to perform requests but exposes a testing facade for verifying responses. WebTestClient can be used to perform end-to-end HTTP tests.
🌐
Baeldung
baeldung.com › home › spring › mocking a webclient in spring
Mocking a WebClient in Spring | Baeldung
January 8, 2024 - Mocking the fluent Spring WebClient interface for testing is possible but hard work. MockWebServer is an easy to use alternative.
Discussions

junit - How to unit test the Spring WebClient in java? - Stack Overflow
Unit testing WebClient has very low ROI. I would recommend looking at WireMock that provides very good API for testing web clients. More on stackoverflow.com
🌐 stackoverflow.com
How to unit test Spring WebClient?
With mockwebserver you can do that. You just need to mock the expected reponse for each test More on reddit.com
🌐 r/SpringBoot
19
6
February 11, 2025
Kotlin Coroutines + Spring Boot
Hi, If you want to use the functional Web DSL with Coroutines, yes it is required to use the WebFlux starter. Typical use case for IO is to use Coroutines API for the http client with WebClient or Coroutines API for persistence with Spring Data R2DBC (Reactive SQL) or Spring Data Reactive NoSQL APIs. You can dispatch manually if you are using blocking APIs. Suspending functions are viral by nature so yes it is expected to see them propagated widely. JUnit 5 does not provide yet support for suspending functions, so you can probably use the short version of what you tried : fun testFoo() = runBlocking { ... }. Not sure about that one. Probably dispatch like you do if the files are big. More on reddit.com
🌐 r/Kotlin
2
1
December 18, 2020
RestClient vs. WebClient vs RestTemplate - Using the suitable library to call REST API in Spring ‌Boot
Databrokers? nope. Social networks? Also nope. This post was deleted using Redact . fade aware public salt sip resolute truck childlike theory absorbed More on reddit.com
🌐 r/SpringBoot
7
32
February 7, 2025
🌐
Shouldn't Be Hard
arhohuttunen.com › spring-boot-webclient-mockwebserver
Testing Spring Boot WebClient With MockWebServer | Shouldn't Be Hard
May 22, 2021 - Learn how to test REST calls with Spring WebClient using integration tests and a mock server for reliable, maintainable tests.
Top answer
1 of 3
6

Unit testing WebClient has very low ROI. I would recommend looking at WireMock that provides very good API for testing web clients. Here are some examples

stubFor(get(url)
        .withHeader(HttpHeaders.ACCEPT, containing(MediaType.APPLICATION_JSON_VALUE))
        .willReturn(aResponse()
                .withStatus(200)
                .withBody("{}")
        )
);

StepVerifier.create(service.callApi())
        .expectNextCount(1)
        .verifyComplete();

You could easily test both positive and negative scenarios by providing different stubs

stubFor(get(url)
        .withHeader(HttpHeaders.ACCEPT, containing(MediaType.APPLICATION_JSON_VALUE))
        .willReturn(aResponse()
                .withStatus(500)
        )
);

In addition, you could test retry logic using Scenarios or even simulate timeouts using Delays.

To initialize it you could use @AutoConfigureWireMockprovided by org.springframework.cloud:spring-cloud-contract-wiremock or, as an alternative, you can add direct dependency to WireMock and initialize it explicitly.

2 of 3
1

We use Wiremock to test Client functionality. It can be done in standard unit test or a SpringBoot test.

Below code explains the Unit testing in regular tests.

@Service
class MoviesClient {
  private final WebClient moviesWebClient;

  public Mono<Movie> findMovieById(String movieID) {
    return moviesWebClient.get().uri(MOVIE_ENDPOINT+"/"+movieID).bodyValue(job).retrieve()
        .bodyToMono(Movie.class);
  }
}

Now as we see MoviesClient needs webClient to call the movie service and get movie.

  @ExtendWith({MockitoExtension.class})
    class MoviesClientTest {
    
        private MoviesClient moviesClient;
        
        @RegisterExtension
          private static final WireMockExtension MOVIES_WM =
         WireMockExtension.newInstance().options(wireMockConfig().port("8086")).build();
        
        @BeforeEach
        void setup() {
        
        var webClient = WebClient.builder().baseUrl("http://localhost:8086")
                .defaultHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE).build();
        moviesClient = new MoviesClient(moviesClient)
MOVIES_WM.stubFor(get(MOVIE_ENDPOINT+"/"+"1234")).withHeader(CONTENT_TYPE, matching(APPLICATION_JSON_VALUE))willReturn(aResponse().withStatus(OK.value()).withHeader(CONTENT_TYPE, APPLICATION_JSON_VALUE)
            .withBody("Your json response body comes here")));
        }
}

Now you can write your tests to call the method on client which in turn will make a webclient call which will be stubbed to wiremock server.

@Test
void testMoviesEndPoint() {
  StepVerifier.create(moviesClient.findMovieById(1234)
  .expectNext(movie -> assertThat(movie).getId.equals(1234))
  .verifyComplete();

FLUENT_WM.verify(1, postRequestedFor(urlEqualTo(MOVIE_ENDPOINT+"/"+"1234")));
}
🌐
Medium
medium.com › @meet2sudhakar › complete-guide-testing-spring-webclient-rest-apis-31fbcd589e6b
Complete Guide: Testing Spring WebClient & REST APIs | by Meet2sudhakar | Medium
November 29, 2025 - // Set timeout on WebClient Mono<User> result = webClient.get() .uri("/users/1") .retrieve() .bodyToMono(User.class) .timeout(Duration.ofSeconds(2)); // Simulate slow response mockWebServer.enqueue(new MockResponse() .setBodyDelay(5, TimeUnit.SECONDS));StepVerifier.create(result) .expectError(TimeoutException.class) .verify(); @Test void shouldOpenCircuitBreakerAfterFailures() { // Enqueue multiple failures for (int i = 0; i < 5; i++) { mockWebServer.enqueue(new MockResponse() .setResponseCode(500)); } // First few calls fail for (int i = 0; i < 5; i++) { try { client.getUser(1L).block(); } catch (Exception e) { // Expected } } // Circuit should be open, no more requests StepVerifier.create(client.getUser(1L)) .expectError(CircuitBreakerOpenException.class) .verify(); }
🌐
Spring
docs.spring.io › spring-framework › reference › web › webflux-webclient › client-testing.html
Testing :: Spring Framework
To test code that uses the WebClient, you can use a mock web server, such as OkHttp MockWebServer or WireMock.
Find elsewhere
🌐
DZone
dzone.com › coding › frameworks › spring boot webclient and unit testing
Spring Boot WebClient and Unit Testing
July 11, 2019 - In this article, we learned both how to make HTTP calls using WebClient and how to write unit test cases designed for testing the functionality.
🌐
Reddit
reddit.com › r/springboot › how to unit test spring webclient?
r/SpringBoot on Reddit: How to unit test Spring WebClient?
February 11, 2025 -

Is it possible to unit test a Spring WebClient by mocking it?

The only examples I come across are integration tests using MockWebserver, WireMock or Hoverfly which does not mock WebClient components but rather instantiates the whole WebClient and mocks the actual backend that the WebClient should connect to.

🌐
DZone
dzone.com › culture and methodologies › career development › unit tests for spring's webclient
Unit Tests for Spring's WebClient - DZone
September 25, 2019 - Here, a server is being brought up at a random port; it is then injected with behavior, and then the client is tested against this server and validated. This approach works and there is no muddling with the internals of WebClient in mocking this behavior, but technically, this is an integration test and will be slower to execute than a pure unit test.
🌐
CalliCoder
callicoder.com › spring-5-reactive-webclient-webtestclient-examples
Spring 5 WebClient and WebTestClient Tutorial with Examples | CalliCoder
February 18, 2022 - WebClient is a non-blocking, reactive HTTP client with a fluent functional style API. It is part of Spring WebFlux module that was introduced in Spring 5. In this article, you'll learn how to use WebClient and WebTestClient to consume and test ...
🌐
Medium
medium.com › geekculture › spring-boot-webclient-testing-techniques-93381b3c9710
Spring Boot WebClient Testing Techniques | by Stanislav Vain | Geek Culture | Medium
April 7, 2023 - WebClient, a non-blocking, reactive client for performing HTTP requests, is widely used in Spring WebFlux applications. In this article, we will explore three popular tools for testing WebClient: MockWebServer, Mockito, and WireMock.
🌐
Mimacom
blog.mimacom.com › spring-webclient-testing
Testing Spring WebClient with MockWebServer | mimacom
October 16, 2020 - // Testing with Spring WebFlux and WebClient class TodoServiceTest { private static MockWebServer mockWebServer; private static TodoService todoService; @BeforeAll static void beforeAll() { mockWebServer = new MockWebServer(); todoService = new TodoService(WebClient.builder(), mockWebServer.url("/").url()); } @AfterAll static void afterAll() throws IOException { mockWebServer.close(); } @Test void shouldReturnTodoDtos() { mockWebServer.enqueue( new MockResponse() .setResponseCode(200) .setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .setBody("[]") ); assertThat(this.todoService.findTodos().collectList().block()).isEqualTo(Collections.emptyList()); } } The full source code for this example is available in this Github project.
🌐
Medium
lucasgarciarubio.medium.com › how-to-write-unit-tests-for-webclient-e112a3012830
How to write unit tests for WebClient | by Lucas Garcia | Medium
August 14, 2023 - How to write unit tests for WebClient This is a straightforward guide on how to test WebClient from Spring WebFlux using MockWebServer, a class offered by OkHttp. What this guide covers: Unit test …
🌐
Baeldung
courses.baeldung.com › courses › 2463040 › lectures › 52134950
Lesson 1: End-To-End API Tests - WebTestClient | Baeldung - Learn
The Spring WebTestClient, a non-blocking, reactive client for testing web servers · In this lesson, we’ll be using Spring’s WebTestClient feature. At first, this might not be the most intuitive decision because our project is based on a ...
🌐
HowToDoInJava
howtodoinjava.com › home › spring boot 2 › spring boot test › spring boot @webfluxtest and webtestclient with junit 5
Spring Boot @WebFluxTest and WebTestClient with JUnit 5
September 13, 2023 - To write integration tests which ... It is a non-blocking, reactive client for testing web servers that uses the reactive WebClient internally to perform requests and provides a fluent API to verify responses....
🌐
Learninjava
learninjava.com › 4-ways-to-test-webclient-mocking
4 Ways to test WebClient using Mockito, MockWebServer, WebTestClient and WireMockServer
May 12, 2020 - Mocking a WebClient in Spring: Learn how to test WebClient, examples include testing using Mockito, MockWebServer, WebTestClient and WireMockServer.
🌐
rieckpil
rieckpil.de › home › spring framework tutorials › spring webtestclient for efficient rest api testing
Spring WebTestClient for Efficient REST API Testing - rieckpil
August 27, 2021 - Alongside the WebClient, Spring provides a WebTestClient for testing purposes. The API of this class is similar to the WebClient and allows the assertion of all parts of the HTTP response.
🌐
Dimitr
dimitr.im › testing-spring-webclient
Dimitr
August 6, 2021 - We cannot provide a description for this page right now
🌐
Dimitri's tutorials
dimitri.codes › testing-spring-webclient
Testing code using Spring's WebClient | Dimitri's tutorials
June 8, 2021 - If you’re developing a reactive application, that is certainly the case. However, if you’re not writing a reactive application and you want to use WebClient, this is not a bad thing to do. If you want to write tests for this piece of logic, one option could be to mock the WebClient.