我有一个带有JSON array 有效负载的服务,例如:
[{ message: "one"}, {message: "two"}]
如何使用spring-restdocs
对此进行记录?
MessageContract contractOne = new MessageContract();
contractOne.setMessage("one");
List list = new ArrayList<>();
list.add(contractOne);
this.webTestClient
.post().uri("/messages")
.body(BodyInserters.fromObject(list))
.exchange().expectStatus().isCreated().expectBody()
.consumeWith(document("POST messages",
requestParameters(
parameterWithName("message").description("Massage we should save"),
))
);
我遇到一个错误:
org.springframework.restdocs.snippet.SnippetException:
Request parameters with the following names were not found in the request:
[message, ...]
我认为restdocs不会看到字段,因为它与数组有关。。如何正确处理?
已添加
:资源:
@PostMapping
private Mono<ResponseEntity> postMessage(@RequestBody List<MessageContract> contract) {
return service
.save(contract)
.collectList()
.thenReturn(new ResponseEntity(HttpStatus.CREATED));
}
答案 0 :(得分:1)
我刚刚为您创建了一个小测试,以显示requestFields.fieldWithPath
数组文档。
请验证,此方法对您有效。
@Test
public void documentRequestBodyArray() {
webTestClient
.post()
.uri("/contract")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.syncBody(List.of(new MessageContract("one"), new MessageContract("two")))
.exchange()
.expectStatus().isOk()
.expectBody()
.consumeWith(document("documentArray",
requestFields(
fieldWithPath("[]").description("a message array"),
fieldWithPath("[].message").description("a message"))));
}
这里的MessageContract
如下:
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class MessageContract {
private String message;
}