java
type_error
ai_generated
true
无法模拟/间谍化最终类:Mockito 无法模拟最终类
org.mockito.exceptions.base.MockitoException: Cannot mock/spy class com.example.FinalClass because Mockito cannot mock final classes
ID: java/mockito-spy-on-final-class
80%修复率
88%置信度
0证据数
2024-05-08首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 8+ | active | — | — | — |
根因分析
Mockito 默认无法模拟或间谍化最终类(需要 mockito-inline 或 Mockito 5+)。
English
Mockito cannot mock or spy on final classes by default (requires mockito-inline or Mockito 5+).
解决方案
-
90% 成功率 Use Mockito 5+ which supports mocking final classes by default
// Upgrade to Mockito 5.x in build.gradle // testImplementation 'org.mockito:mockito-core:5.0.0'
-
85% 成功率 Add mockito-inline dependency
// Add to build.gradle // testImplementation 'org.mockito:mockito-inline:5.2.0'
无效尝试
常见但无效的做法:
-
Removing final keyword from production code
50% 失败
Changes production code design; may not be allowed.
-
Using PowerMockito
40% 失败
Adds heavy dependency and may cause compatibility issues.