Rest-Assured报Content-Type为null异常,请求未进入控制器问题排查
解决Rest-Assured测试中
Cannot parse object because no supported Content-Type was specified异常 我之前也踩过类似的坑,咱们一步步拆解问题,找到根源:
1. 先确认请求是否真的到达了你的控制器
你提到请求线程没进入控制器方法,这说明请求可能在到达控制器之前就被拦截或处理了:
- 用IDE调试功能,在
DispatcherServlet的doDispatch方法上打个断点,看看请求是否进入了Spring的处理流程; - 或者添加一个简单的过滤器,打印所有请求的URL、头信息,确认请求的正确性:
@Component public class RequestLoggingFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { System.out.println("Request URL: " + request.getRequestURL()); System.out.println("Accept Header: " + request.getHeader("Accept")); filterChain.doFilter(request, response); } }
2. 检查Rest-Assured的请求配置是否正确
确保你设置Accept头的方式没有问题,Rest-Assured提供了两种常用方式,别写错位置:
// 方式1:使用内置的ContentType枚举 given() .accept(ContentType.JSON) .when() .get("/your-api-endpoint") .then() .statusCode(200); // 方式2:手动设置Header given() .header("Accept", "application/json") .when() .get("/your-api-endpoint") .then() .statusCode(200);
注意:accept()或者header()必须放在given()块里,而不是when()或者then()之后,否则不会生效。
3. 排查后端的Content-Type配置问题
即使你在@GetMapping里指定了produces,也可能被其他配置覆盖:
- 检查控制器类上的
@RequestMapping是否也设置了produces,类级别的配置会覆盖方法级别的; - 查看项目中是否有
WebMvcConfigurer实现类,修改了内容协商策略(比如优先使用请求参数而非Accept头),这会导致你设置的produces失效; - 可以先临时去掉
produces属性,让Spring自动协商Content-Type,看是否能正常返回JSON,再逐步添加回来定位问题。
4. 检查是否是容器默认响应导致的Content-Type为null
如果请求的URL错误(比如拼写错误、缺少上下文路径),后端会返回容器(如Tomcat)的默认错误响应(比如404),这类响应通常没有设置Content-Type头,从而触发Rest-Assured的报错:
- 确认请求URL是否完全正确,包括项目的上下文路径(如果设置了
server.servlet.context-path); - 可以先直接用浏览器或者Postman请求该端点,看是否能正常返回JSON,同时检查响应头里的
Content-Type是否存在。
5. 临时绕过Content-Type检查(用于排查)
如果以上步骤还没找到问题,可以让Rest-Assured强制用JSON解析响应,忽略Content-Type为null的情况:
// 全局配置,所有请求生效 RestAssured.config = RestAssured.config() .jsonConfig(jsonConfig().defaultContentTypeName(ContentType.JSON)); // 单个请求生效 YourResponseClass response = given() .accept(ContentType.JSON) .when() .get("/your-api-endpoint") .then() .extract() .body() .as(YourResponseClass.class, new JsonPathConfig().defaultContentTypeName(ContentType.JSON));
这样可以拿到响应内容,判断是后端没返回数据,还是响应头配置的问题。
6. 检查全局异常处理器的响应配置
如果请求在进入控制器之前抛出了异常(比如参数校验失败、权限拦截),全局异常处理器(@RestControllerAdvice)返回的响应如果没有设置Content-Type,也会导致这个问题:
- 检查异常处理器的方法,确保返回响应时设置了正确的Content-Type,比如:
@RestControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity<ErrorResponse> handleException(Exception e) { ErrorResponse error = new ErrorResponse("ERROR", e.getMessage()); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR) .contentType(MediaType.APPLICATION_JSON) // 必须设置这个 .body(error); } }
内容的提问来源于stack exchange,提问作者Maciej Rudnicki
相关产品推荐
相关产品推荐

