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

Mockito参数不一致+空指针异常:WebTestClient Put测试问题排查

测试用例参数匹配失败的原因分析

原测试代码

@Test
void checkPutProfileNotFound() {
    ProfileDto profileDto = new ProfileDto("abcd@gmail.com", "abcd", null, null);
    when(profileService.putProfile(profileDto)).thenReturn(Mono.error(new NotFoundException()));
    webTestClient.put().uri("/profile/put")
            .bodyValue(profileDto)
            .exchange();
    verify(profileService, times(1)).putProfile(profileDto);
}

报错信息

Argument(s) are different! Wanted:
com.example.profile.service.ProfileService#0 bean.putProfile(
    ProfileDto(email=abcd@gmail.com, name=abcd, dob=null, number=null)
);
-> at com.example.profile.controller.ProfileControllerTest.checkPutProfileNotFound(ProfileControllerTest.java:115)
Actual invocations have different arguments:
com.example.profile.service.ProfileService#0 bean.putProfile(
    ProfileDto(email=abcd@gmail.com, name=abcd, dob=null, number=null)
);

错误原因

  • 参数匹配逻辑的本质问题
    Mockito默认用equals()方法判断参数是否匹配,但如果ProfileDto类没有正确重写equals()和hashCode()方法,Mockito会自动 fallback 到引用比较——也就是严格检查传入的对象是不是同一个实例。

  • 对象实例不一致
    你在测试代码里创建了一个profileDto实例,传给when()和verify(),但当webTestClient发送请求时,Spring WebFlux会把请求体反序列化成全新的ProfileDto实例。虽然两个实例的内容完全一样,但它们是不同的对象,引用地址不同,所以Mockito判定参数不匹配。

  • NullPointerException的由来
    因为参数不匹配,你设置的存根逻辑(返回Mono.error)根本没生效。Mockito对未存根的方法调用会返回默认值,对于Mono类型来说,默认返回空Mono,后续代码处理空Mono时就会触发NullPointerException。

  • 用any()解决的原因
    any(ProfileDto.class)(或简写any())是Mockito的宽松匹配器,它不检查对象的内容或引用,只要参数是ProfileDto类型就会匹配,所以存根逻辑能正常触发,验证也能通过。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 09:40:24