【问题标题】:I want to test to my controller method which consume=MediaType.MULTIPART_FORM_DATA_VALUE only我想测试我的控制器方法,它只消耗=MediaType.MULTIPART_FORM_DATA_VALUE
【发布时间】:2021-08-16 08:02:33
【问题描述】:

我正在使用 mockMvc 进行测试。如何在 mockMVc.perform 中发送 PaymentOrderDto 对象值,我可以在控制器方法中接收。

如 PaymentOrderDto.setMid("m1") 等

@PostMapping(consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces= MediaType.APPLICATION_JSON_VALUE)

public ResponseEntity<String> createPaymentOrder(HttpServletRequest request, PaymentOrderDto paymentOrderDto,
                                                     @RequestPart(required = false) MultipartFile paymentReceiptFile,
                                                     @RequestParam(value = "contactId", required = true) String contactId,
                                                     HttpServletResponse response) {
                        
--method  body                           

}

List item

【问题讨论】:

    标签: java unit-testing mockito mockmvc springmockito


    【解决方案1】:

    你可以这样做;

    控制器端点;

    @PostMapping(value = "createPaymentOrder", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, produces= MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> createPaymentOrder(HttpServletRequest request,
                                                     @RequestPart PaymentOrderDto paymentOrderDto,
                                                     @RequestPart(required = false) MultipartFile paymentReceiptFile,
                                                     @RequestParam(value = "contactId", required = true) String contactId,
                                                     HttpServletResponse response) {
        return new ResponseEntity<String>(contactId + ":" + paymentOrderDto.getMid(), HttpStatus.OK);
    }
    

    测试功能;

    @Test
    void testMe() throws Exception {
        MockMultipartFile employeeJson = new MockMultipartFile("paymentOrderDto", null,
                "application/json", "{\"mid\": \"10\"}".getBytes());
        mockMvc.perform(MockMvcRequestBuilders.multipart("/createPaymentOrder")
                .file(employeeJson)
                //.file("") --> paymentReceiptFile which is not mandatory
                .accept(MediaType.parseMediaType("application/json"))
                .param("contactId", "C1")
                .contentType(MediaType.MULTIPART_FORM_DATA_VALUE))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json"))
                .andDo(print())
                .andExpect(mvcResult -> "C1:10".equals(mvcResult));
    }
    

    【讨论】:

      猜你喜欢
      • 2015-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 2014-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多