WebTestClient
WebTestClient, MOOL RUP SE, REACTIVE (WebFlux) APPLICATIONS ke liye, DESIGN kiya gaya tha, LEKIN, TRADITIONAL, Spring MVC applications ke liye bhi, USE ho sakta hai — EK FLUENT, CHAINABLE API PROVIDE karta hai, JO, MockMvc SE, ZYAADA, MODERN aur READABLE MAANI jaati hai.
END-TO-END, INTEGRATION TESTS ke liye, WebTestClient, REAL, RUNNING SERVER (@SpringBootTest(webEnvironment = RANDOM_PORT)) ke SAATH bhi, USE ho sakta hai — ACTUAL, NETWORK-LEVEL, HTTP CALLS, TRIGGER karta hai.
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
class ProductApiIntegrationTest {
@Autowired
private WebTestClient webTestClient;
@Test
void shouldGetProduct() {
webTestClient.get().uri("/api/products/1")
.exchange()
.expectStatus().isOk()
.expectBody()
.jsonPath("$.name").isEqualTo("Laptop");
}
@Test
void shouldCreateProduct() {
webTestClient.post().uri("/api/products")
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(new ProductCreateDto("Mouse", new BigDecimal("25")))
.exchange()
.expectStatus().isCreated();
}
}- WebTestClient = reactive AUR traditional, DONO ke saath, kaam karta hai
- Fluent, chainable API — MockMvc se, MODERN style
- @SpringBootTest(RANDOM_PORT) ke saath, REAL, end-to-end testing bhi possible
WebTestClient, expectBodyList() aur, returnResult().getResponseBodyContent() SE, STREAMING, RESPONSES (jaise, Server-Sent Events, YA, REACTIVE, STREAMS) ko, TEST kar sakta hai — MockMvc, ISME, UTNA, NATURAL NAHI hai, kyunki, WOH, PRIMARILY, TRADITIONAL, MVC ke liye, DESIGN kiya gaya THA.
WebTestClient.builder().responseTimeout(Duration.ofSeconds(10)).build() — LONG-RUNNING, OPERATIONS (jaise, ASYNC, PROCESSING) ko, TEST karte waqt, DEFAULT, TIMEOUT (TYPICALLY, 5 SECONDS), BADHANA, ZAROORI ho sakta hai.
WebTestClient client = WebTestClient.bindToServer()
.baseUrl("http://localhost:8080")
.responseTimeout(Duration.ofSeconds(10))
.build();