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

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序列化时也不会输出对应字段,同样会触发该异常。

修复步骤

  1. 修正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;
    }
}
  1. 补全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;
    }
}
  1. (纯单元测试可选优化)如果不需要依赖真实业务逻辑,可在测试类中用@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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 18:54:03