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

Mockito中如何让thenReturn动态返回更新后的参数值?

解决Mockito中thenReturn获取不到更新后值的问题

问题出在thenReturn(ob.getParam())的执行时机:当你定义mock行为时,ob.getParam()会立即执行并返回当时的5,这个值被固定下来,后续即使Param更新,mock返回的还是这个旧值。

要动态获取更新后的值,改用Mockito的thenAnswer()方法就行,它会在实际调用mock方法时才计算返回值:

@Test
void test() {
  ob.setParam(5);
  // 用thenAnswer动态获取最新的param值
  when(otherClassMock.otherMethod()).thenAnswer(invocation -> ob.getParam());
  ob.myMethod();
}

这里的lambda表达式会在otherClassMock.otherMethod()被调用时触发,此时ob的Param已经被myMethod()更新,所以能拿到最新值。

如果是Mockito旧版本(不支持lambda),可以用匿名内部类实现Answer接口:

when(otherClassMock.otherMethod()).thenAnswer(new Answer<Integer>() {
    @Override
    public Integer answer(InvocationOnMock invocation) throws Throwable {
        return ob.getParam();
    }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 11:00:46