How do you mock generic types in a type-safe manner?

67 Views Asked by At

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
}
1

There are 1 best solutions below

4
knittl On

Newer versions of Mockito have "magic" mock() method that can infer the Mock's type automatically:

final GenericType<ImportantTypeArgument> genericType = mock();

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());