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

MockHttpServletResponse未返回模拟列表,实体序列化空值问题排查

问题分析与解决方案

问题根源

你的Book实体类缺少属性的getter方法。Spring MVC使用Jackson进行JSON序列化时,默认需要通过getter方法访问对象属性,而你当前仅使用@NoArgsConstructor和@AllArgsConstructor注解——这两个注解仅生成构造方法,不会生成getter/setter方法,导致Jackson无法读取属性值,最终序列化出空对象{}。

解决方案

给Book类添加getter方法,最简单的方式是使用Lombok的@Data注解(自动生成getter、setter、toString等通用方法),或者单独使用@Getter注解:

修改后的Book实体类(使用@Data)

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String author;
    private String description;
}

或单独使用@Getter

@Entity
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class Book {
    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String author;
    private String description;
}

验证修改

重新运行测试后,MockHttpServletResponse的响应体将包含完整属性值(例如[{"id":1,"title":"Book 1","author":"Author 1","description":"Description 1"},...]),jsonPath("$[0].id").value(1L)的断言也会成功通过。

内容的提问来源于stack exchange,提问作者Juan Diego Lozano

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 05:15:43