Improved support for generic types in 5.2.0

26 views
Skip to first unread message

Jörg von Frantzius

unread,
Mar 10, 2023, 6:24:00 AM3/10/23
to mockito
Hi,
I'm happy that PR Feature 2921 generic types by jfrantzius · Pull Request #2923 · mockito/mockito (github.com) was merged, which provides improved support for generic types with @Mock and @Injection.

Previously, it was easy to step into the trap of adding just another @Mock field with a generic type to your class under test and suddenly see your test fail, without any reasons given. You'd then have to know that your @Mock field has to have the same name as the @InjectMock's field, which non-expert users just aren't aware of. IMHO, this has led to users distrusting @Mock and @InjectMock in general, and simply stop using them, as they failed in common use-cases without any obvious reasons or remedy.

Despite Java's type erasure, Mockito now knows from Java's generic type information where to inject which @Mock field e.g. here:

public class UnderTestWithTypeParameters<T1, T2> {
List<T1> t1List;
List<T2> t2List;
}

@Mock
List<String> stringList;

@Mock
List<Integer> intList;

@InjectMocks
UnderTestWithTypeParameters<String, Integer> underTestWithTypeParameters = new UnderTestWithTypeParameters<String, Integer>();


The feature is available with Release v5.2.0 · mockito/mockito (github.com), thx TimvdLippe for reviewing + merging.

Cheers,
Jörg
Reply all
Reply to author
Forward
0 new messages