spring SnippetException:无法记录响应字段,因为响应正文为空

dm7nw8vv  于 2023-11-16  发布在  Spring
关注(0)|答案(2)|浏览(113)

这是我的控制器:

@PostMapping("post")
@PreAuthorize("hasAuthority('WRITE')")
public ResponseEntity<?> createPost(@RequestBody PostEntity postEntity) {
    return new ResponseEntity<>(postService.createPost(postEntity), HttpStatus.CREATED);
}

字符串
服务内容:

@Override
public Post createPost(PostEntity postEntity) {
    return postFactory.buildPost(postEntityRepository.save(postEntity));
}

//Post is Immutable class here
    public Post buildPost(PostEntity entity) {
        return new Post.Builder()
                .groupId(entity.getGroupEntity().getGroupId())
                .postedBy(entity.getPostedBy().getUsername())
                .postType(entity.getType())
                .postMedia(entity.getPostMedia())
                .postId(entity.getPostId())
                .build();
    }


下面是我的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())
                    ));


下面是Post call:

@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
        }
    }


Post实体类:

@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)

bfnvny8b

bfnvny8b1#

问题出在“PostMedia”setter“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);
        }
    
   }

字符串

ukxgm1gy

ukxgm1gy2#

将版本从1.5.5更改为1.5.8解决了这个问题。<asciidoctor.version>1.5.8</asciidoctor.version>并在pom.xml中具有此依赖关系

<dependency>
            <groupId>org.springframework.restdocs</groupId>
            <artifactId>spring-restdocs-mockmvc</artifactId>
        </dependency>

字符串

相关问题