@InjectMocks ignores @Mock's name of generic type
Author: GhedeonCreated May 3, 2017Updated Jun 16, 2026
Labelsinjection
When injecting two fields of the same type with @InjectMocks, the @Mock's name is not taken into account.
public class Foo {
Bar<Integer> f1;
Bar<Boolean> f2;
public Foo(Bar<Integer> f1, Bar<Boolean> f2) {
this.f1 = f1;
this.f2 = f2;
}
}interface Bar<T> {
}@RunWith(MockitoJUnitRunner.class)
public class FooTest {
@Mock(name = "f1")
Bar<Integer> f1;
@Mock(name = "f2")
Bar<Boolean> f2;
@InjectMocks
Foo foo;
@Test
public void test() {
System.out.println(foo.f1);
System.out.println(foo.f2);
}
}Expected result: f1 mock --> f1, and f2 mock --> f2. Actual result: f1 mock is getting injected into both fields.
Version: mockito-core:2.7.22
Source: mockito/mockito