mockito中when().thenreturn()用于对mock对象方法打桩返回值,核心是先mock()创建模拟对象,再用when(mock.method()).thenreturn(value)指定行为,不支持final/static/私有方法,void方法需用dothrow()等替代。

在 Java 中用 Mockito 的 when 打桩返回值,核心是先用 mock() 创建模拟对象,再用 when(...).thenReturn(...) 指定方法调用时的返回结果。
基本写法:when + thenReturn
这是最常用的打桩方式,适用于无参或有参的普通方法:
UserService mockUserService = mock(UserService.class);
when(mockUserService.findById(123)).thenReturn(new User("Alice"));
when(mockUserService.getName()).thenReturn("Bob");
注意:when 的括号里必须是**对 mock 对象方法的调用**(不能是真实对象或静态方法),且该方法不能是 final、static 或私有方法(默认 Mockito 不支持)。
处理多个参数或不同入参的返回值
可以用匹配器(如 eq()、anyInt()、anyString())让打桩更灵活:
when(service.process(eq("data"), anyInt())).thenReturn(true);when(service.findUser(any())).thenReturn(null);- 连续多次调用返回不同值:
when(mockDao.get()).thenReturn("first").thenReturn("second");
打桩 void 方法或抛异常
when 不能用于 void 方法。此时改用 doThrow() 或 doAnswer() 等 doXXX 系列:
doThrow(new RuntimeException("timeout")).when(mockService).save(user);
doAnswer(invocation -> {
System.out.println("save called with: " + invocation.getArgument(0));
return null;
}).when(mockService).save(any());
常见陷阱提醒
- 不要对真实对象调用
when—— 会真正执行原方法,可能引发 NPE 或副作用 - 避免混用
mock和spy:spy 是部分模拟,when(spy.method())可能意外触发真实逻辑 - 使用
MockitoJUnitRunner或@ExtendWith(MockitoExtension.class)确保测试干净隔离
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











