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

JUnit Springboot MockMvc测试异常:预期null却返回ScanRequestDTO

问题解决:MockMvc测试验证ModelAttribute类型报错

问题根源

你在测试里用了Mockito的any(ScanRequestDTO.class)作为匹配器,但MockMvc的model().attribute()断言依赖的是Hamcrest匹配器,不是Mockito的。Mockito的any()在这里会被解析为null,导致测试预期模型属性是null,但实际Spring MVC会自动初始化一个空的ScanRequestDTO实例(所有字段为null),所以出现了预期和实际不匹配的错误。

解决方案

把Mockito的any()替换成Hamcrest的instanceOf()匹配器,用来验证模型属性的类型是否正确。

修正后的测试代码

import org.hamcrest.Matchers;

@Test
void doScanTest() throws Exception {
    this.mockMvc.perform(get("/web/doscan"))
        .andExpect(model().attribute("scanRequestDTO", Matchers.instanceOf(ScanRequestDTO.class)))
        .andExpect(view().name("doScan"))
        .andExpect(status().isOk());
}

额外说明

如果后续需要验证ScanRequestDTO的字段值,比如确认所有字段初始为null,可以用Hamcrest的hasProperty匹配器:

.andExpect(model().attribute("scanRequestDTO", Matchers.allOf(
    Matchers.instanceOf(ScanRequestDTO.class),
    Matchers.hasProperty("name", Matchers.nullValue()),
    Matchers.hasProperty("dateOfBirth", Matchers.nullValue())
)))

内容的提问来源于stack exchange,提问作者BjarneSlamon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 04:23:13