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

如何让Mockito的ArgumentCaptor在未捕获参数时返回null?

实现可返回null的ArgumentCaptor

问题场景

当前使用ArgumentCaptor的代码如下,当producer.accept(win)被调用时能正常返回捕获到的Win对象,但如果该方法未被调用,会抛出断言错误,期望此时返回null:

public Win getWin() {
    ArgumentCaptor<Win> winCaptor = ArgumentCaptor
            .forClass(Win.class);
    Mockito.verify(producer, Mockito.atMostOnce()).accept(winCaptor.capture());
    return winCaptor.getValue();
}

未捕获到参数时的错误信息:

No argument value was captured!
You might have forgotten to use argument.capture() in verify()...
...or you used capture() in stubbing but stubbed method was not called.
Be aware that it is recommended to use capture() only with verify()

解决方案

方案一:先判断方法调用状态(推荐)

先验证方法调用次数,再决定是否执行参数捕获逻辑,避免触发断言错误:

public Win getWin() {
    // 先验证方法最多被调用一次,不触发参数捕获
    Mockito.verify(producer, Mockito.atMostOnce()).accept(Mockito.any());
    
    // 检查方法是否实际被调用过
    boolean isAcceptCalled = Mockito.mockingDetails(producer).getInvocations()
            .stream()
            .anyMatch(invocation -> "accept".equals(invocation.getMethod().getName()));
    
    if (isAcceptCalled) {
        ArgumentCaptor<Win> winCaptor = ArgumentCaptor.forClass(Win.class);
        Mockito.verify(producer).accept(winCaptor.capture());
        return winCaptor.getValue();
    }
    
    return null;
}

方案二:捕获断言异常(简洁但需谨慎)

利用Mockito未调用方法时抛出的MockitoAssertionError,通过try-catch控制流程:

public Win getWin() {
    ArgumentCaptor<Win> winCaptor = ArgumentCaptor.forClass(Win.class);
    try {
        // 验证方法被调用并捕获参数
        Mockito.verify(producer).accept(winCaptor.capture());
        return winCaptor.getValue();
    } catch (MockitoAssertionError e) {
        // 方法未被调用时返回null
        return null;
    }
}

注意:此方式会捕获所有Mockito断言错误,若存在其他验证逻辑,可能掩盖真实问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:12:53