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

如何用Mockito模拟final类静态方法使其调用时无实际执行

解决Mockito-inline模拟Final类静态方法失效的问题

问题原因

你当前的测试代码没有对Webber的静态方法做显式mock配置,Mockito不会自动拦截静态方法调用——哪怕已经引入了mockito-inline依赖。

解决方案步骤

  1. 确认依赖配置正确性
    确保pom.xml中mockito-inline依赖版本不低于3.4.0(该版本开始支持final类、静态方法的mock),依赖示例:
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <version>4.11.0</version>
    <scope>test</scope>
</dependency>
  1. 修改测试代码,显式静态mock
    使用Mockito的MockedStatic模拟Webber类的静态方法,并且必须通过try-with-resources管理mock资源,避免影响其他测试:
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;

@InjectMocks
CustomerService customerService;

@Mock
AddCustomerProfile addCustomerProfile;

@BeforeEach
void setUp() {
    // 初始化Mocks
    MockitoAnnotations.openMocks(this);
}

@Test
public void saveCustomer() {
    // 模拟Webber的静态方法,拦截addMessageToResponse调用
    try (Mockito.MockedStatic<Webber> mockedWebber = Mockito.mockStatic(Webber.class)) {
        // 指定方法调用时的行为:什么都不执行
        mockedWebber.when(() -> Webber.addMessageToResponse(any(Message.class)))
                   .thenAnswer(invocation -> null);

        // 执行被测方法
        customerService.saveCustomer(addCustomerProfile);

        // 可选:验证静态方法是否被调用过一次
        mockedWebber.verify(() -> Webber.addMessageToResponse(any(Message.class)), times(1));
    }
}
  1. 关键注意事项
  • MockedStatic必须在try-with-resources块中使用,确保测试结束后自动释放静态mock,避免污染其他测试用例
  • 方法匹配要准确:如果需要匹配特定的Message对象,可以替换any(Message.class)为具体的参数匹配器
  • 确保导入的是org.mockito.Mockito下的静态方法,避免混淆其他类

内容的提问来源于stack exchange,提问作者John K Jose

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 03:42:42