Here is a working example:

@Component
public class QuotesClient {

  private final WebClient webClient;

  public QuotesClient(WebClient.Builder builder, @Value("${client.baseUrl}") String baseUrl) {
    this.webClient = builder.baseUrl(baseUrl).build();
  }

  public JsonNode getData() {
    return this.webClient
      .get()
      .retrieve()
      .bodyToMono(JsonNode.class)
      .block();
  }
}

Using the WebClient.Builder is optional.

The corresponding test can look like the following:

class QuotesClientTest {

  private QuotesClient quotesClient;
  private MockWebServer server;

  @BeforeEach
  public void setup() {
    this.server = new MockWebServer();
    this.quotesClient = new QuotesClient(WebClient.builder(), server.url("/").toString());
  }

  @Test
  public void test() {

    server.enqueue(new MockResponse()
      .setStatus("HTTP/1.1 200")
      .setBody("{\"bar\":\"barbar\",\"foo\":\"foofoo\"}")
      .addHeader("Content-Type", "application/json"));

    JsonNode data = quotesClient.getData();
    assertNotNull(data);

    System.out.println(data);

  }

}

If you are searching for a similar setup using WireMock, Spring Boot, and JUnit 5, take a look at the linked guide.

Answer from rieckpil on Stack Overflow
🌐
Baeldung
baeldung.com › home › spring › mocking a webclient in spring
Mocking a WebClient in Spring | Baeldung
January 8, 2024 - Using MockWebServer is recommended by the Spring Team for writing integration tests.
🌐
rieckpil
rieckpil.de › home › spring framework tutorials › test spring webclient with mockwebserver from okhttp
Test Spring WebClient with MockWebServer from OkHttp - rieckpil
August 27, 2021 - Write tests for your Spring WebClient usage with OkHttp's MockWebServer and mock HTTP responses to test different scenarios
🌐
Industrial Logic
industriallogic.com › blog › better-integration-testing-with-mockwebserver
Better Integration Testing with MockWebServer
April 13, 2022 - Setting the addFilters to false turns off security so you don’t have to pass an auth token to call your endpoint. As of Spring 5.3 (Spring Boot 2), the @WebAppConfiguration annotation is no longer needed for MockMvc to work. The MockWebServer is started in the @BeforeAll setup and stopped in the @AfterAll and is set to a field.
🌐
Industrial Logic
industriallogic.com › blog › integration-testing-with-mockwebserver
Integration Testing with MockWebServer
February 15, 2021 - As many of you know, Spring is deprecating RestTemplate and replacing it with WebClient. Mocking a server with RestTemplate was done with Spring’s MockRestServiceServer, which was able to mock the endpoint your service would normally call. There is a way to almost replicate that functionality using MockWebServer (okhttp).
🌐
Shouldn't Be Hard
arhohuttunen.com › spring-boot-webclient-mockwebserver
Testing Spring Boot WebClient With MockWebServer | Shouldn't Be Hard
May 22, 2021 - To replace the remote service with a mock service, we can use MockWebServer. This library lets us run a lightweight web server locally in our tests. The library allows us to specify which response to return and then verify the requests we made.
🌐
Medium
medium.com › @swarts_uk › testing-spring-boot-webclient-with-mockwebserver-815478f5b484
Testing Spring Boot WebClient with MockWebServer | by Swarts UK | Medium
April 17, 2021 - In this post, we will look at how to use WebClient to make a call to a 3rd party API and test it. Instead of calling the API itself we will mock it with a MockWebServer which is a lightweight web server that can receive and respond to HTTP requests.
🌐
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
🌐
Medium
jskim1991.medium.com › spring-boot-using-mockwebserver-for-integration-tests-499030f6bfff
[Spring Boot] Using WireMock and MockWebServer for Spring WebFlux Integration Tests | by Jay Kim | Medium
August 8, 2023 - This article covers how to configure WireMock and MockWebServer for a Spring WebFlux application to stub for any external APIs the application might need.
🌐
Spring
docs.spring.io › spring-framework › docs › current › javadoc-api › org › springframework › mock › web › server › package-summary.html
org.springframework.mock.web.server (Spring Framework 7.0.7 API)
A comprehensive set of Servlet API 6.0 mock objects, targeted at usage with Spring's Web MVC framework · Extension of DefaultServerWebExchange for use in tests, along with MockServerHttpRequest and MockServerHttpResponse · Implementation of WebSession that delegates to a session instance ...
🌐
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.
🌐
Bobsantosjr
bobsantosjr.com › springboot-spock-mockwebserver
Using MockWebServer with Spring Boot and Spock - Bob Santos Jr.
We can use MockWebServer as is or we can use a library from fabric8 that wraps MockWebServer and gives us a nice DSL. Or do as I’ve done and create our own simple wrapper around MockWebServer. We will be using Spring Boot and Spock for this example. We’ll be using RestTemplate to call external services.
🌐
Stack Overflow
stackoverflow.com › questions › 72358534 › unit-testing-on-springboot-webclient-with-mockwebserver
spring boot - Unit Testing on Springboot WebClient with MockWebServer - Stack Overflow
May 24, 2022 - @ExtendWith(MockitoExtension::class) @MockitoSettings(strictname = Strictness.LENIENT) @TestInstance(TestInstance.Lifecycle.PER_CLASS) class ApiServiceTest { @Mock private lateinit var webClient: WebClient @InjectMocks private lateinit var mockApiService: ApiService private val mockName = "mockName" private val mockDetailDto = DetailDto(name = "mockName", age = 18) @Test fun canGetDetails() { mockWebServer.enqueue( MockResponse() .setResponse(200) .addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .setBody(mockDetailDto)) ) mockApiService.getApiResult(mockName) val request: RecordedRequest = mockWebServer.takeRequest() // Assert statements with request } }
🌐
How to do in Java
howtodoinjava.com › home › java libraries › getting started with mockwebserver and junit
Getting Started with MockWebServer and JUnit
July 11, 2022 - In this tutorial, we will learn to setup MockWebServer in JUnit 5 tests. We will be using Spring WebClient as HTTP client to invoke the mocked APIs.
🌐
javathinking
javathinking.com › blog › how-to-set-mockwebserver-port-to-webclient-in-junit-test
How to Set MockWebServer Dynamic Port to WebClient in Spring Boot JUnit Tests — javathinking.com
The challenge is overriding weather.api.base-url (from application.properties) to use MockWebServer’s dynamic port in tests. Spring Boot 2.2+ provides @DynamicPropertySource, which lets you dynamically set configuration properties at test runtime.
🌐
GitHub
github.com › spring-projects › spring-boot › issues › 14223
Provide MockWebServer Integration · Issue #14223 · spring-projects/spring-boot
August 28, 2018 - For example, a user of Spring Boot's Security OAuth2 support might want to provide a value for spring.security.oauth2.resourceserver.jwt.issuer-uri that points to the MockWebServer.
Author: spring-projects