【问题标题】:how to write spring-restdocs snippets with MockMultipartFile如何使用 MockMultipartFile 编写 spring-restdocs 片段
【发布时间】:2016-05-12 08:31:13
【问题描述】:

我将 spring 单元测试与 spring-restdocs 一起使用。

这是我的 mockmvc 代码:

mockMvc.perform(fileUpload("/api/enterprise/uploadImage")
                .file(imageFile)
                .with(csrf().asHeader())
                .params(params)
).andExpect(status().isOk());

但是当使用 spring-restdocs 时,我不知道如何编写文件的 sn-p。

这是我的 sn-ps 创建代码:

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)

【问题讨论】:

    标签: java spring spring-mvc spring-restdocs


    【解决方案1】:

    您正在发送一个多部分请求,因此正在上传的文件不是请求参数。相反,它是请求中的一部分,并且 您的测试失败,因为您试图记录一个不存在的请求参数。

    Spring REST Docs 目前不支持在多部分请求中记录部分。有一个open issue for it。我还没有实现任何东西,因为请求部分可能非常复杂。例如,在某些情况下,部件名称和描述可能就足够了,但在其他情况下,记录部件的标题、其内容的结构等可能很有用。

    请对上面链接的问题发表评论,特别是如果对最简单情况的支持有用的话。

    【讨论】:

    • 谢谢你。我使用了请求部件文档的自定义实现。并解决这个问题。
    【解决方案2】:

    spring-restdocs1.1.0.RELEASE 版本发布以来,您可以使用RequestPartsSnippet

    您现在可以使用 MockMultipartFile 编写 spring-restdocs sn-ps,如下所示:

    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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多