SpringBoot MockMvc测试报No value at JSON path "name"异常解决方案问询
问题排查与修复方案
异常含义
你遇到的java.lang.AssertionError: No value at JSON path "name"异常,本质是MockMvc断言时,无法从接口返回的JSON响应中解析到name字段。
根因分析
CarController的getCar方法使用了private修饰符,Spring MVC要求请求映射方法必须是public修饰才能被正确注册为接口处理逻辑,同时该方法直接返回null,导致接口响应体为空,没有对应的JSON结构。- 若
Car实体类没有对应name、type属性的getter方法,就算返回Car对象,Jackson序列化时也不会输出对应字段,同样会触发该异常。
修复步骤
- 修正Controller层代码:将
getCar方法修饰符改为public,构造返回合法的Car对象
@RestController public class CarController { @GetMapping("/cars/{name}") public Car getCar(@PathVariable String name) { // 实际业务可替换为调用Service层查询逻辑 Car car = new Car(); car.setName(name); car.setType("diesel"); return car; } }
- 补全Car实体类的getter/setter方法
package com.nix.tdd.domain; public class Car { private String name; private String type; public Car() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } }
- (纯单元测试可选优化)如果不需要依赖真实业务逻辑,可在测试类中用
@MockBean模拟业务层返回,避免耦合业务实现:
@RunWith(SpringRunner.class) @WebMvcTest(CarController.class) public class CarControllerTest { @Autowired private MockMvc mockMvc; // 注入模拟的Service @MockBean private CarService carService; @Test public void getCar_ShouldReturnCar() throws Exception{ // 模拟Service返回结果 when(carService.queryByName("dezire")).thenReturn(new Car("dezire", "diesel")); this.mockMvc.perform(get("/cars/dezire")) .andExpect(status().isOk()) .andExpect(jsonPath("name").value("dezire")) .andExpect(jsonPath("type").value("diesel")); } }
内容的提问来源于stack exchange,提问作者boopathi
相关产品推荐
相关产品推荐

