Are there more type-safe alternatives to this (other than mocking a non-generic subtype of a generic type)?
@Test
@SuppressWarnings("unchecked")
void test() {
GenericType<ImportantTypeArgument> genericType = mock(GenericType.class);
// the rest of the test
}
A more concrete example:
@Test
@SuppressWarnings("unchecked")
void getHeadersFilter_ifNull_delegatesToInjectedObjectProvider() {
HttpHeadersFilter filterMock = mock(HttpHeadersFilter.class);
// this line includes an unchecked cast
ObjectProvider<List<HttpHeadersFilter>> headersFiltersProviderMock = mock(ObjectProvider.class);
given(headersFiltersProviderMock.getIfAvailable()).willReturn(List.of(filterMock));
// the rest of the test
}
Newer versions of Mockito have "magic"
mock()method that can infer the Mock's type automatically:This method overload actually accepts a varargs array (with zero elements in this specific case). The type of the array can be picked up by the compiler, even if no actual arguments have been provided.
Alternatives:
final GenericType<ImportantTypeArgument> genericType = Mockito.<GenericType<ImportantTypeArgument>>mock(GenericType.class);final GenericType<ImportantTypeArgument> genericType = mock(new TypeToken<GenericType<ImportantTypeArgument>>(){}.getRawType());