When developing a controller webflux on post request in the parameters of the controller, I pass the request body using the annotation, but in webtestclient method return 400 BAD_REQUEST
My DTO:
@AllArgsConstructor
@Data
public class VisitRequest {
private String description;
public static Visit createEntityFromDto(Long customerId, Long deviceId, VisitRequest visitRequest) {
return new Visit(null, customerId, deviceId, visitRequest.getDescription(),
null);
}
}
My Controller:
@RestController
@RequestMapping(value = VisitController.REST_URL)
@AllArgsConstructor
@Slf4j
public class VisitController {
static final String REST_URL = "/api/customers/{customerId}/devices/{deviceId}";
private final VisitService visitService;
//POST http://visits-service/api/customers/{customerId}/devices/{deviceId}/visits
@PostMapping(value = "/visits", produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<Visit> save(@PathVariable("customerId") @Validated long customerId,
@PathVariable("deviceId") @Validated long deviceId,
@RequestBody VisitRequest visitRequest) {
log.info("save {} for customer_id: {}, device_id {}", visitRequest, customerId, deviceId);
return visitService.save(createEntityFromDto(customerId, deviceId, visitRequest))
.switchIfEmpty(error(new RuntimeException("Bad request for save visit:" + visitRequest)));
}
}
My Test class with WebTestClient:
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = VisitApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class VisitControllerTest {
@LocalServerPort
private int port;
@Test
void save() throws Exception {
WebTestClient
.bindToServer()
.baseUrl("http://localhost:" + port)
.build()
.post()
.uri("/api/customers/" + ONE.getCustomerId()
+ "/devices/" + ONE.getDeviceId() + "/visits")
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON)
.bodyValue(new VisitRequest("test"))
.exchange()
.expectStatus().isCreated()
.expectHeader().valueEquals("Content-Type", MediaTypes.ALPS_JSON_VALUE);
}
}
When I run the test, WebTestClient return:
> POST http://localhost:63028/api/customers/10000/devices/20000/visits
> WebTestClient-Request-Id: [1]
> Content-Type: [application/json]
> Accept: [application/json]
> Content-Length: [22]
{"description":"test"}
< 400 BAD_REQUEST Bad Request
< Content-Type: [application/json]
< Content-Length: [169]
{"timestamp":"2020-09-27T19:28:09.987+00:00","path":"/api/customers/10000/devices/20000/visits","status":400,"error":"Bad Request","message":"","requestId":"42d54765-1"}
When I put a breakpoint on the logging line in the save method controller in the IntelliJ IDEA, and when I run the test in debug, the controller returns a bad request before reaching the breakpoint
Please help me find the cause of the error