如何使用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
相关产品推荐
相关产品推荐

