我想测试我的 Spring 控制器,它有输入 json 和多部分文件,但是即使该功能有效,我也无法让测试工作我尝试使用 MockMvcRequestBuilders.fileUpload 但测试总是得到 405控制器: @PutMapping(value = "/upload", consumes = {"multipart/form-data"}) public BaseResponse<SomeModel> updateSomeModelContent( @ApiIgnore @Valid @ModelAttribute MandatoryRequest mandatoryRequest, @PathVariable("id") String id, @RequestParam("file") MultipartFile file, @RequestParam("json") String json) throws IOException { final CommonSomeModelRequest request = JSONHelper.convertJsonInStringToObject(json, CommonSomeModelRequest.class); return makeResponse(someModelSer.updateContent(id, request, mandatoryRequest, file)); }考试: @Test public void updateCountryContentSuccessTest() throws Exception { MockMultipartFile file1 = new MockMultipartFile("file", "filename-1.jpeg", "image/jpeg", "some-image".getBytes()); MockMultipartFile file2 = new MockMultipartFile("json", "", "application/json","{\"exampleAttr\": \"someValue\"}".getBytes()); when(this.someModelService .updateContent(id, request, MANDATORY_REQUEST, file1)) .thenReturn(someModelUpdatedContent); MockHttpServletRequestBuilder builder = MockMvcRequestBuilders .fileUpload("/upload/{id}", id) .file(file1) .file(file2) .requestAttr("mandatory", MANDATORY_REQUEST); this.mockMvc.perform(builder) .andExpect(status().isOk()); verify(this.someModelService) .updateContent(id, request, MANDATORY_REQUEST, file1); }结果状态一直是405,不知道怎么变成200
1 回答

肥皂起泡泡
TA贡献1829条经验 获得超6个赞
MockMvcRequestBuilders.multipart(...)
createMockMultipartHttpServletRequestBuilder
只支持POST。但在你的控制器中你使用 POST。您应该在其余控制器中将 PUT 更改为 POST 映射。
另外根据 RFC,我们应该在分段上传上使用 POST 而不是 PUT。
添加回答
举报
0/150
提交
取消