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 OverflowBaeldung
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.
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.
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.
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 } }
Spring
docs.spring.io › spring-ws › site › apidocs › org › springframework › ws › test › client › MockWebServiceServer.html
MockWebServiceServer (Spring Web Services 2.1.4.RELEASE API)
Creates a MockWebServiceServer instance based on the given WebServiceGatewaySupport.
Spring
docs.spring.io › spring-framework › docs › current › javadoc-api › org › springframework › mock › web › server › MockServerWebExchange.html
MockServerWebExchange (Spring Framework 7.0.2 API)
declaration: package: org.springframework.mock.web.server, class: MockServerWebExchange