我正在尝试记录使用spring rest文档返回所有者列表的方法,但我不知道如何记录Hateoas提供的链接。
linkWithRel(...)在_embedded.ownerDtoList对象上不起作用。
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class OwnerDto extends RepresentationModel<OwnerDto> {
@Null
private UUID id;
@NotBlank
@Size(min = 3, max = 20)
private String name;
}
@GetMapping(value = "")
public ResponseEntity<CollectionModel<OwnerDto>> getOwners() {
List<OwnerDto> owners = ownerService.findAllOwners();
HttpHeaders headers = new HttpHeaders();
headers.add("X-Owners-Total", Integer.toString(owners.size()));
owners.stream().map(owner -> owner
.add(linkTo(OwnerController.class).slash(owner.getId()).withSelfRel())
.add(linkTo(OwnerController.class).withRel("owners")))
.collect(Collectors.toList());
Link mainSelfLink = linkTo(OwnerController.class).withSelfRel();
return new ResponseEntity<>(
new CollectionModel<>(owners, mainSelfLink),
headers,
HttpStatus.OK
);
}
public void findAllOwners() throws Exception {
List<OwnerDto> ownerDtoList = Arrays.asList(ownerDto_1, ownerDto_2);
Mockito.when(ownerService.findAllOwners()).thenReturn(ownerDtoList);
mockMvc.perform(get("/api/v1/owner")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$._embedded.ownerDtoList[0].id", is(ownerDto_1.getId().toString())))
.andExpect(jsonPath("$._embedded.ownerDtoList[0].name", is(ownerDto_1.getName())))
.andExpect(jsonPath("$._embedded.ownerDtoList[1].id", is(ownerDto_2.getId().toString())))
.andExpect(jsonPath("$._embedded.ownerDtoList[1].name", is(ownerDto_2.getName())))
.andExpect(header().longValue("X-Owners-Total", 2L))
.andDo(document("v1/{method-name}", ownerPageHeadersSnippet(), ownerCollectionResponseFieldsSnippet(),
links(
halLinks(),
linkWithRel("owners").description("Get all owners <<Resource>>"),
linkWithRel("self").description("Self <<Resource>>")
)
));
}
{
"_embedded": {
"ownerDtoList": [
{
"id": "9eccbed8-6184-470c-b635-7d7bd4196caf",
"name": "Szymaa",
"_links": {
"self": {
"href": "http://localhost:8088/api/v1/owner/9eccbed8-6184-470c-b635-7d7bd4196caf"
},
"owners": {
"href": "http://localhost:8088/api/v1/owner"
}
}
},
{
"id": "f0edf088-d1ff-49dc-9561-e65ab0dcd645",
"name": "dsad23",
"_links": {
"self": {
"href": "http://localhost:8088/api/v1/owner/f0edf088-d1ff-49dc-9561-e65ab0dcd645"
},
"owners": {
"href": "http://localhost:8088/api/v1/owner"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8088/api/v1/owner"
}
}
}
org.springframework.restdocs.snippet.SnippetException:在响应中找不到具有以下关系的链接:[所有者]
答案 0 :(得分:0)
Spring REST Docs不支持此功能。建议的方法不是将嵌入资源的链接作为嵌入每个资源的文档的一部分进行记录,而是建议链接到嵌入资源的文档。对于您而言,这将是指向ownerDtoList
资源(我怀疑可以作为http://localhost:8088/api/v1/owner的文档)的链接。
如果您希望在所有嵌入的资源链接上进行文档记录,则可以实现自定义LinkExtractor
并使用它代替halLinks()
。
您可以在this Spring REST Docs issue中进一步了解上述内容。