我使用spring单元测试和spring-restdocs。
这是我的mockmvc代码:
mockMvc.perform(fileUpload("/api/enterprise/uploadImage")
.file(imageFile)
.with(csrf().asHeader())
.params(params)
).andExpect(status().isOk());但是当使用spring-restdocs时,我不知道如何编写文件的片段。
这是我的代码片段创建代码:
document.snippets(
requestParameters(
parameterWithName("file").description("upload file"),
parameterWithName("imageType").description("image type")
)
);这样我就会得到一个错误:
org.springframework.restdocs.snippet.SnippetException: Request parameters with the following names were not found in the request: [file]
at org.springframework.restdocs.request.RequestParametersSnippet.verificationFailed(RequestParametersSnippet.java:79)
at org.springframework.restdocs.request.AbstractParametersSnippet.verifyParameterDescriptors(AbstractParametersSnippet.java:93)
at org.springframework.restdocs.request.AbstractParametersSnippet.createModel(AbstractParametersSnippet.java:70)
at org.springframework.restdocs.snippet.TemplatedSnippet.document(TemplatedSnippet.java:64)
at org.springframework.restdocs.mockmvc.RestDocumentationResultHandler.handle(RestDocumentationResultHandler.java:101)
at org.springframework.test.web.servlet.MockMvc.applyDefaultResultActions(MockMvc.java:195)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:163)
at com.athena.edge.enterprise.controller.UploadImageTest.uploadImage(UploadImageTest.java:108)发布于 2016-05-12 18:12:51
您正在发送一个由多部分组成的请求,因此正在上传的文件不是一个请求参数。相反,它是请求中的一个部分,您的测试失败了,因为您试图记录一个不存在的请求参数。
Spring REST文档目前不支持在多部分请求中记录部分。有一个open issue for it。我还没有实现任何东西,因为请求部分可能非常复杂。
请对链接到上面的问题发表评论,特别是如果支持最简单的情况将是有用的。
发布于 2020-08-12 15:59:39
自spring-restdocs的1.1.0.RELEASE版本发布以来,您可以使用RequestPartsSnippet。
您现在可以使用MockMultipartFile编写spring-restdocs代码片段,如下所示:
mockMvc.perform(multipart("/upload").file("file", "example".getBytes()))
.andExpect(status().isOk())
.andDo(document("upload", RequestPartsSnippet.requestParts(
RequestPartDescriptor.partWithName("file").description("The file to upload"))
));此示例取自官方文档here。
https://stackoverflow.com/questions/37181396
复制相似问题