Spring Boot CashCard API测试报错:org.opentest4j.AssertionFailedError(406)
排查Spring Boot测试中406 NOT_ACCEPTABLE错误的原因与解决方法
错误原因分析
406 NOT_ACCEPTABLE表示服务器无法生成客户端请求中Accept头指定格式的响应。结合你的代码,核心问题有两个:
- CashCard实体无法被序列化:Spring Boot默认用Jackson将Java对象转为JSON,但你的
CashCard类没有定义属性,也没有提供getter方法,Jackson无法读取对象数据,导致无法生成合法的JSON响应。 - Controller方法未绑定路径参数:
@GetMapping("/{requestedId}")声明了路径参数,但findById()方法没有接收该参数,破坏了Spring的请求处理逻辑,也会导致后续业务逻辑异常。
解决步骤
1. 修复CashCard实体类
为CashCard添加属性和getter方法,确保Jackson能正常序列化对象:
package com.stephane.cashcard.Entity; public class CashCard { private final Long cardId; private final Double amount; // 构造方法初始化属性 public CashCard(Long cardId, Double amount) { this.cardId = cardId; this.amount = amount; } // 添加getter方法供Jackson读取数据 public Long getCardId() { return cardId; } public Double getAmount() { return amount; } }
如果希望JSON返回的字段名为id而非cardId,可以在cardId属性或getCardId()方法上添加@JsonProperty("id")注解
2. 修复Controller的路径参数绑定
在findById()方法中添加@PathVariable注解接收路径参数:
package com.stephane.cashcard.Controller; import com.stephane.cashcard.Entity.CashCard; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/cashcards") public class CashCardController { @GetMapping("/{requestedId}") public ResponseEntity<CashCard> findById(@PathVariable Long requestedId) { // 后续可替换为数据库查询逻辑 CashCard cashCard = new CashCard(requestedId, 0.0); return ResponseEntity.ok(cashCard); } }
3. 同步调整测试类的JSON字段读取
如果实体类的JSON字段名有变更(比如改成id),需要修改测试中的JSON路径:
// 若实体字段对应JSON的key是id Number id = documentContext.read("$.id"); // 若实体字段对应JSON的key是cardId Number id = documentContext.read("$.cardId");
验证修复
重新运行测试,此时Spring可正常将CashCard序列化为JSON响应,客户端TestRestTemplate的请求头能匹配到合法的响应格式,测试会返回200 OK,断言通过。
内容的提问来源于stack exchange,提问作者Boguhe Stephane
相关产品推荐
相关产品推荐

