java
config_error
ai_generated
true
无法实例化 @InjectMocks 字段 'service',类型为 'class com.example.MyService'
org.mockito.exceptions.base.MockitoException: Cannot instantiate @InjectMocks field named 'service' of type 'class com.example.MyService'
ID: java/mockito-injectmocks-failure
80%修复率
87%置信度
0证据数
2024-10-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 8+ | active | — | — | — |
根因分析
@InjectMocks 需要无参构造函数或构造函数注入,但类缺少无参构造函数或有歧义的构造函数。
English
@InjectMocks requires a no-arg constructor or constructor injection, but class lacks one or has ambiguous constructors.
解决方案
-
90% 成功率 Provide a no-arg constructor in production class
public MyService() { // default constructor } -
85% 成功率 Use manual construction with mocks
MyService service = new MyService(mockDep1, mockDep2);
无效尝试
常见但无效的做法:
-
Adding @InjectMocks to a field with private constructor
70% 失败
Mockito cannot instantiate the class.
-
Using @Spy on the same field
50% 失败
Spy requires an instance; @InjectMocks is for creating instances.