12.3.2 Testing POST requests
WebTestClient can do more than just test GET requests against controllers. It can also be used to test any kind of HTTP method. Table 12.1 maps HTTP methods to WebTestClient methods.
Table 12.1 WebTestClient tests any kind of request against Spring WebFlux controllers.
| HTTP method | WebTestClient method |
|---|---|
GET | .get\(\) |
POST | .post\(\) |
PUT | .put\(\) |
PATCH | .patch\(\) |
DELETE | .delete\(\) |
HEAD | .head\(\) |
As an example of testing another HTTP method request against a Spring WebFlux controller, let’s look at another test against TacoController. This time, you’ll write a test of your API’s taco creation endpoint by submitting a POST request to /api/tacos as follows:
@SuppressWarnings("unchecked")
@Test
public void shouldSaveATaco() {
TacoRepository tacoRepo = Mockito.mock(
TacoRepository.class);
WebTestClient testClient = WebTestClient.bindToController(
new TacoController(tacoRepo)).build();
Mono<Taco> unsavedTacoMono = Mono.just(testTaco(1L));
Taco savedTaco = testTaco(1L);
Flux<Taco> savedTacoMono = Flux.just(savedTaco);
when(tacoRepo.saveAll(any(Mono.class))).thenReturn(savedTacoMono);
testClient.post()
.uri("/api/tacos")
.contentType(MediaType.APPLICATION_JSON)
.body(unsavedTacoMono, Taco.class)
.exchange()
.expectStatus().isCreated()
.expectBody(Taco.class)
.isEqualTo(savedTaco);
}As with the previous test method, shouldSaveATaco() starts by mocking TacoRepository, building a WebTestClient that’s bound to the controller, and setting up some test data. Then, it uses the WebTestClient to submit a POST request to /api/tacos, with a body of type application/json and a payload that’s a JSON-serialized form of the Taco in the unsaved Mono. After performing exchange(), the test asserts that the response has an HTTP 201 (CREATED) status and a payload in the body equal to the saved Taco object.
