Spring SnippetException:无法记录响应字段,因为响应正文为空
这是我的控制器:Spring SnippetException:无法记录响应字段,因为响应正文为空,spring,spring-boot,spring-restdocs,Spring,Spring Boot,Spring Restdocs,这是我的控制器: @PostMapping("post") @PreAuthorize("hasAuthority('WRITE')") public ResponseEntity<?> createPost(@RequestBody PostEntity postEntity) { return new ResponseEntity<>(postService.createPost(postEntity), HttpStatus.CREATED); } 这是
@PostMapping("post")
@PreAuthorize("hasAuthority('WRITE')")
public ResponseEntity<?> createPost(@RequestBody PostEntity postEntity) {
return new ResponseEntity<>(postService.createPost(postEntity), HttpStatus.CREATED);
}
这是我的mockMvc:
@BeforeEach
public void setUp(WebApplicationContext webApplicationContext,
RestDocumentationContextProvider restDocumentation) {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext)
.apply(documentationConfiguration(restDocumentation))
.alwaysDo(document("{method-name}",
preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint())))
.build();
}
这是我的测试:
this.mockMvc.perform(post("/api/post")
.contentType(MediaTypes.HAL_JSON)
.contextPath("/api")
.content(this.objectMapper.writeValueAsString(postEntity)))
.andExpect(status().isCreated())
.andDo(
document("{method-name}", preprocessRequest(prettyPrint()),
preprocessResponse(prettyPrint()),
requestFields(describeCreatePostRequest()),
responseFields(describePostEntityResult())
));
以下是邮寄电话:
@Value.Immutable
@JsonSerialize(as = ImmutablePost.class)
@JsonDeserialize(as = ImmutablePost.class)
@JsonInclude(JsonInclude.Include.NON_NULL)
@Relation(value = "post", collectionRelation = "posts")
public interface Post {
Long getPostId();
String getPostType();
String postedBy();
@Nullable
PostMedia postMedia();
Long groupId();
class Builder extends ImmutablePost.Builder {}
}
PostEntity@Entity类这里是json格式:
{
"type" : "text",
"postedBy" : {
"username": "sandeep"
},
"postMedia" : {
"mediaType": "text",
"mediaUrl": "null",
"content": "Hi this is testing media content",
"createdAt": 1234,
"updatedAt": 689
},
"groupEntity": {
"groupId": 4
}
}
和后实体类:
@Entity
@Table(name = "POST")
@JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class PostEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "POST_ID")
private Long postId;
@Column(name = "POST_TYPE")
private String type;
@ManyToOne
@JoinColumn(name = "username", referencedColumnName = "username")
private User postedBy;
@OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "post_media_id", referencedColumnName = "id")
private PostMedia postMedia;
@ManyToOne(cascade = CascadeType.REMOVE, fetch = FetchType.LAZY)
@JoinColumn(name = "GROUP_ID", referencedColumnName = "GROUP_ID")
private GroupEntity groupEntity;
public PostEntity() {
}
}
我试过了
objectMapper.readValue(objectMapper.writeValueAsString(postEntity), ImmutablePost.class);
还有。但它仍然不起作用,我面临着同样的例外:
org.springframework.restdocs.snippet.SnippetException: Cannot document response fields as the response body is empty
at org.springframework.restdocs.payload.AbstractFieldsSnippet.verifyContent(AbstractFieldsSnippet.java:191)
at org.springframework.restdocs.payload.AbstractFieldsSnippet.createModel(AbstractFieldsSnippet.java:147)
at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:78)
at org.springframework.restdocs.generate.RestDocumentationGenerator.handle(RestDocumentationGenerator.java:191)
问题在于PostMedia设置程序PostMedia和GroupEntity。您需要接受setters参数中的字符串,并将其转换为相应的实体。期望setter的参数作为自定义实体类型是造成问题的原因 例如:
public class MyModel {
private CustomEnum myEnum;
public CustomEnum getMyEnum() {
return myEnum;
}
public void setMyEnum(String enumName) {
this.myEnum = CustomEnum.valueOf(enumName);
}
}
向其发出POST请求的端点返回了什么?它似乎返回了一个带有空正文的响应,因此对文档的响应中没有任何内容。@Andy Wilkinson实际上API在保存后返回相同的对象。在我的例子中,我将在请求中传递实体,并在对象获得savedIt后返回不可变对象,因为响应似乎没有主体。你能提供一个完整的例子来说明所涉及的一切吗?@AndyWilkinson我已经试着把整个流程放在这里了,如果你还需要其他东西来更新,请告诉我,但事情仍然不完整。例如,没有Post类,因此我无法使用您的代码重现问题。欢迎使用Stack Overflow,并感谢您的贡献。
public class MyModel {
private CustomEnum myEnum;
public CustomEnum getMyEnum() {
return myEnum;
}
public void setMyEnum(String enumName) {
this.myEnum = CustomEnum.valueOf(enumName);
}
}