You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot RestController的JUnit+Mockito测试报错:Content type未设置

解决Mockito测试Spring Boot RestController的Content-Type问题

嘿,我一眼就看到问题所在啦!你的测试失败主要是两个关键地方出了问题,咱们一步步来修复:

1. 修复Controller的核心逻辑错误

你的getImageById方法犯了一个基础错误:返回的ResponseEntity只传递了状态码,没有把查询到的Image对象作为响应体返回!这样Spring没法自动设置Content-Type,而且响应体是空的,导致MockMvc的jsonPath断言无法解析内容。

修改后的Controller方法应该这样写:

@RestController
@RequestMapping("/project/image")
public class ImageController {
    @Autowired
    ImgService imageService;

    @GetMapping("/getImage/{id}")
    public ResponseEntity<Image> getImageById(@PathVariable Integer id) {
        Optional<Image> img = imageService.getImageById(id);
        // 处理Optional的两种情况:找到则返回对象+200,没找到返回404
        return img.map(image -> new ResponseEntity<>(image, HttpStatus.OK))
                  .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }
    // ...其他方法
}

这样当查询到图片时,Spring会自动将响应体序列化为JSON,并设置Content-Type: application/json,完美解决Content-Type未设置的问题。

2. 修正测试中的请求路径

你的Controller类上有@RequestMapping("/project/image")前缀,但测试里的请求路径只写了/getImage/{id},这会导致请求找不到对应的接口(实际应该是/project/image/getImage/{id})。虽然当前报错是Content-Type,但路径错误也会引发后续异常,所以必须修正:

修改后的测试方法:

@Test
@DisplayName("GET /project/image/getImage/1 - Found")
void testGetImageIdFound() throws Exception {
    Image mockImage = new Image(1, "mockPath", "Normal");
    doReturn(Optional.of(mockImage)).when(service).getImageById(1);

    mockMvc.perform(get("/project/image/getImage/{id}", 1)
                   .accept(MediaType.APPLICATION_JSON_UTF8))
           .andExpect(status().isOk()) // 先断言状态码是200
           .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8)) // 断言Content-Type正确
           .andExpect(jsonPath("$.id", is(1)))
           .andExpect(jsonPath("$.path", is("mockPath")))
           .andExpect(jsonPath("$.status", is("Normal"))); // 可以多断言几个字段,让测试更严谨
}

额外说明

为什么会触发Content type not set错误?因为当你只返回new ResponseEntity<>(HttpStatus.OK)时,响应体是空的,Spring不会自动设置Content-Type头。而jsonPath断言需要解析JSON格式的响应体,必须依赖正确的Content-Type,所以就抛出了这个错误。

内容的提问来源于stack exchange,提问作者Fadi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 15:12:26