You need to enable JavaScript to run this app. 如何使用Mockito-inline验证android.util.Log静态i方法的调用参数
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Mockito-inline验证android.util.Log静态i方法的调用参数

解决方案

错误原因

你原来的代码编译不通过是因为Mockito对静态类mock的验证语法和普通对象mock不同:MockedStatic的verify方法需要传入一个包含待验证静态方法调用的lambda表达式,不能直接调用logMock.i()。

前置依赖

首先确保你引入的是支持静态mock的mockito-inline,而非普通的mockito-core,gradle依赖配置如下:

testImplementation 'org.mockito:mockito-inline:3.8.0'

正确的测试代码

import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.mockStatic;

import org.mockito.MockedStatic;
import android.util.Log;

@Test
public void test_log() {
    // 用try-with-resources声明静态mock的作用域,执行完自动释放
    try (MockedStatic<Log> logMock = mockStatic(Log.class)) {
        Intent intent = getIntent();
        // 执行业务代码
        Util.handleIntent(intent, "theTag", "+++TEST1");
        // 验证静态方法调用,方法调用写在lambda的执行块中
        logMock.verify(
            () -> Log.i(eq("theTag"), eq("+++TEST1")),
            times(1)
        );
    }
}

额外注意点

  • 静态mock的作用域仅在try-with-resources代码块内生效,不会污染其他测试用例的执行
  • 如果你是跑本地JVM单元测试,不需要额外引入Android相关的日志依赖,mock后的Log类会直接替换原有android.jar中的空实现stub

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 15:06:03