【问题标题】:MockMvc Test does not get to the endpoint for a Multipart file in a RestControllerMockMvc 测试未到达 RestController 中的 Multipart 文件的端点
【发布时间】:2020-06-20 11:03:44
【问题描述】:

我在订单控制器中调用服务,该控制器接收多部分文件并对其进行处理并将其保存到数据库中。我正在尝试为它创建一个 Spring Rest Doc,但它甚至没有达到端点。我正在创建一个订单列表,这是服务所期望的。如图所示,它以流的形式接收订单,并在将其保存到数据库之前将其转换为订单流。我已经展示了控制器的主要部分和生成其余文档的代码。当我运行代码时,我得到以下异常,当我设置断点时,它甚至从未到达端点。我也使用了 fileupload() 但这也不起作用。

例外是:

内容类型 = 应用程序/json 正文 = {"path":"/orders/order_reception","exceptionName": "MissingServletRequestPartException","message":"必需的请求部分'uploadFile'不是

现在", "rootExceptionName":"MissingServletRequestPartException", "rootMessage":"MissingServletRequestPartException: 所需的请求部分 'uploadFile' 不存在"}

@RestController
@RequestMapping(value = "/orders")
@Validated
class OrderController{

@PostMapping(path = "/order_reception")

public ResponseEntity receiveData(@RequestPart MultipartFile uploadFile,
                                               HttpServletRequest request,
                                               HttpServletResponse response) {
    if (!uploadFile.isEmpty()) {
        try {
            Reader reader = new InputStreamReader(request.getInputStream()));
            ... save file

            return new ResponseEntity<>(HttpStatus.HttpStatus.CREATED);
        } catch (Exception e) {
            return new ResponseEntity(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
    return new ResponseEntity(HttpStatus.BAD_REQUEST);
}




@Test
 public void sendData() throws Exception {

     ObjectMapper mapper = new ObjectMapper();

     Order order = repository.getOrder("1233333");

     List<Order> orderList = new ArrayList<>():

     resourceList.add(order);

     MockMultipartFile orderFile = new MockMultipartFile("order-data", "order.json", "application/json", 

     mapper.writeValueAsString(orderList).getBytes(Charset.defaultCharset()));

     mockMvc.perform(multipart("/orders/order_reception")
             .file(orderFile))
             .andExpect(status().isCreated())
             .andDo(document("send-order",
                     preprocessRequest(prettyPrint()),
                     preprocessResponse(prettyPrint())));
 }

【问题讨论】:

  • 此处显示的代码与您的异常不匹配,甚至无法编译。但是在您的测试中,您的多部分元素被命名为 order-data 而不是 file 如错误消息所述。
  • 我只添加了不包括导入的部分,因为它太长了。我不使用任何称为文件的标识符。
  • 您根据异常使用该标识符(除非这不是异常),并且代码两次使用相同的方法参数,这使其无效。

标签: spring spring-boot spring-mvc spring-rest


【解决方案1】:

谢谢 Marten Deinum,您提出的文件名错误的建议已修复。 我只是在 MockMultipartFile("uploadsFile", ...) 中更改了名称

【讨论】:

    猜你喜欢
    • 2021-01-20
    • 2019-08-03
    • 1970-01-01
    • 1970-01-01
    • 2019-01-20
    • 2020-08-06
    • 2019-02-17
    • 2019-06-05
    • 1970-01-01
    相关资源
    最近更新 更多