java
config_error
ai_generated
true
org.mockito.exceptions.base.MockitoException: Cannot instantiate @InjectMocks field named 'service' of type 'class com.example.MyService'
ID: java/mockito-injectmocks-failure
80%Fix Rate
87%Confidence
0Evidence
2024-10-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 8+ | active | — | — | — |
Root Cause
@InjectMocks requires a no-arg constructor or constructor injection, but class lacks one or has ambiguous constructors.
generic中文
@InjectMocks 需要无参构造函数或构造函数注入,但类缺少无参构造函数或有歧义的构造函数。
Workarounds
-
90% success Provide a no-arg constructor in production class
public MyService() { // default constructor } -
85% success Use manual construction with mocks
MyService service = new MyService(mockDep1, mockDep2);
Dead Ends
Common approaches that don't work:
-
Adding @InjectMocks to a field with private constructor
70% fail
Mockito cannot instantiate the class.
-
Using @Spy on the same field
50% fail
Spy requires an instance; @InjectMocks is for creating instances.