使用RestAssured测试含MultipartFile参数的Controller时遇Content-Type异常
问题解决方法
问题根源
你的代码存在两个核心问题:
- Controller中同时使用
@RequestParam(MultipartFile)和@RequestBody不符合规范——multipart请求的请求体由多个独立part组成,无法同时用@RequestBody读取整个body为JSON,也不能和文件参数共存。 - RestAssured测试中同时调用
.multiPart()和.body()会导致Content-Type冲突:.body()默认设置application/json,而multipart请求要求Content-Type必须以multipart/开头。
修正步骤
1. 修改Controller代码
将@RequestBody CategoryItemDTO categoryItemDTO改为@RequestPart("categoryItemDTO") @Valid CategoryItemDTO categoryItemDTO,让Spring从multipart请求的对应part中解析JSON;同时显式指定接口接收multipart类型请求:
@PostMapping(value = MENU_CATEGORY_ID, consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public ResponseEntity<Void> addCategoryItem( @PathVariable Long menuCategoryId, @RequestParam("imageFile") MultipartFile imageFile, @Valid @RequestPart("categoryItemDTO") CategoryItemDTO categoryItemDTO) throws IOException { Owner owner = userService.getCurrentOwner(); CategoryItem categoryItem = categoryItemMapper.map(categoryItemDTO); menuCategoryService.addCategoryItemToMenuCategory(menuCategoryId, owner, categoryItem, imageFile); return ResponseEntity.status(HttpStatus.CREATED).build(); }
2. 修改RestAssured测试代码
去掉.body(categoryItemDTO),改用.multiPart()将DTO作为JSON part传入,同时匹配文件的实际Content-Type:
default Response addCategoryItem( final Long menuCategoryId, final File imageFile, final CategoryItemDTO categoryItemDTO ) { return requestSpecification() .pathParam("menuCategoryId", menuCategoryId) .multiPart("imageFile", imageFile, MediaType.IMAGE_PNG_VALUE) // 按文件实际类型设置Content-Type .multiPart("categoryItemDTO", categoryItemDTO, ContentType.JSON) .post(CATEGORY_ITEMS + MENU_CATEGORY_ID) .then() .statusCode(HttpStatus.CREATED.value()) .extract() .response(); }
可移除
urlEncodingEnabled(false),multipart请求默认编码方式兼容常规场景,无特殊需求无需手动关闭。
额外检查
测试中读取文件的路径建议调整为Maven/Gradle项目的标准资源读取方式,避免路径错误:
File file = ResourceUtils.getFile("classpath:static/images/mcchiken.png");
内容的提问来源于stack exchange,提问作者mat92
相关产品推荐
相关产品推荐

