如何用Mockito模拟final类静态方法使其调用时无实际执行
解决Mockito-inline模拟Final类静态方法失效的问题
问题原因
你当前的测试代码没有对Webber的静态方法做显式mock配置,Mockito不会自动拦截静态方法调用——哪怕已经引入了mockito-inline依赖。
解决方案步骤
- 确认依赖配置正确性
确保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>
- 修改测试代码,显式静态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)); } }
- 关键注意事项
MockedStatic必须在try-with-resources块中使用,确保测试结束后自动释放静态mock,避免污染其他测试用例- 方法匹配要准确:如果需要匹配特定的
Message对象,可以替换any(Message.class)为具体的参数匹配器 - 确保导入的是
org.mockito.Mockito下的静态方法,避免混淆其他类
内容的提问来源于stack exchange,提问作者John K Jose
相关产品推荐
相关产品推荐

