Show List
Test using WebTestClient
Let's assume we have a simple controller that handles HTTP requests for a RESTful API:
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;
@RestController
public class HelloController {
@GetMapping("/hello")
public Mono<ResponseEntity<String>> sayHello() {
return Mono.just(ResponseEntity.ok("Hello, World!"));
}
}
Now, let's create JUnit test cases for this controller using WebTestClient:
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.reactive.server.WebTestClient;
import reactor.core.publisher.Mono;
@SpringBootTest
@AutoConfigureWebTestClient
public class HelloControllerTest {
@Autowired
private WebTestClient webTestClient;
@Test
public void testSayHello() {
// Send GET request to /hello endpoint
webTestClient.get().uri("/hello")
.accept(MediaType.APPLICATION_JSON)
.exchange()
// Verify status code and response body
.expectStatus().isOk()
.expectBody(String.class).isEqualTo("Hello, World!");
}
// Additional test cases can be added for error scenarios, etc.
}
In this example:
- We annotate the test class with
@SpringBootTest
to enable Spring Boot test support. - We use
@AutoConfigureWebTestClient
to configure WebTestClient automatically. - We inject an instance of
WebTestClient
using@Autowired
. - In the
testSayHello()
method, we send a GET request to the/hello
endpoint and verify the response using WebTestClient's fluent API. We expect the status code to be OK (200) and the response body to be "Hello, World!". - Additional test cases can be added for handling error scenarios, testing different request parameters, or verifying behavior under specific conditions.
These test cases ensure that the controller behaves correctly and responds appropriately to HTTP requests. They provide confidence in the behavior of the non-blocking API and help catch any regressions or issues introduced during development.
Leave a Comment