spring 测试接受POJO和MultipartFile[]附件的POST端点的正确方法是什么?

6pp0gazn  于 2023-01-29  发布在  Spring
关注(0)|答案(1)|浏览(124)

我是MockMVC的新手。我已经成功地编写了一些基本的测试,但是我在尝试测试一个用例时遇到了麻烦,该用例的端点需要一个带两个参数的POST请求-一个POJO和一个MultipartFile数组。

@Test
 public void vytvorPodnetTest() throws Exception {
 var somePojo = new SomePojo();
 
 somePojo.setSomeVariable("test_value");
 
 var roles = List.of("TEST_USER");
 var uid = "00000000-0000-0000-0000-000000000001";
 
 MockMultipartFile[] attachments = {new MockMultipartFile("file1.txt", "file1.txt", "text/plain", "file1 content".getBytes()),
 new MockMultipartFile("file2.txt", "file2.txt", "text/plain", "file2 content".getBytes())};
 
 MockMultipartHttpServletRequestBuilder builder = MockMvcRequestBuilders.multipart("/some-pojo/create");
 builder.with(req - {
 req.setMethod("POST");
 return req;
         });
 
 MvcResult result = mockMvc.perform(builder.file(attachments[0]).file(attachments[1])
                 .param("SomePojo", new ObjectMapper().writeValueAsString(somePojo))
                         .file(attachment[0])
                 .with(TestUtils.generateJWTToken(uid, roles)))
                 .andExpect(status.isOk())
                 .andReturn();
 }

控制器方法如下:

@PostMapping(value = "/create", consumes = {MediaType.MULTIPART_FORM_DATA_VALUE})
 public UUID createPojo(
             @RequestPart(value = "SomePojo") SomePojo somePojo,
             @RequestPart(value = "attachments", required = false) MultipartFile[] attachments) {
 
 return pojoService.create(somePojo, attachments);
  }

在到达服务之前,它在这里停止。我试着将文件添加为参数“attachments”和如上所示,但我得到的都是“400 Bad Request

djp7away

djp7away1#

最后找到了将参数作为MockMultipartFile从MockMVC发送到控制器的方法:

MockMultipartFile pojoJson = new MockMultipartFile("SomePojo", null,
            "application/json", JsonUtils.toJSON(podnet).getBytes());

    mockMvc.perform(MockMvcRequestBuilders.multipart("/some-pojo/create")
                    .file(pojoJson)
                    .contentType(MediaType.MULTIPART_FORM_DATA_VALUE)
                    .with(new TestUtils().generateJWTToken(uid, roles)))
            .andExpect(status().isOk()).andReturn().getResponse().getContentAsString();

相关问题