I'm using the Mockito mock framework to mock a generic class in Java. The usage of the framework seems to be pretty clear from the documentation, I didn't find an example for mocking generic classes. The mock framework contains the following method:
public static <T> T mock(Class<T> classToMock) {
...
}
I have a generic type IState<StateId, Event>
and I want to instantiate it using the above method. I tried the following:
IState<StateId, Event> mockState = Mockito.mock(IState.class);
I get the following warning for this code:
Type safety: The expression of type IState needs unchecked conversion to conform to IState<StateId,Event>
I think I know what the problem is. The mock
method returns a type of IState
, but the variable I'm assigning to is a specialized type IState<StateId, Event>
, so I somehow need to tell it that the class I am creating is specifically IState<StateId, Event>
, but I don't know what the syntax for this is. I tried the following ones, but they all gave syntax errors.
IState<StateId, Event> mockState = Mockito.mock(IState<StateId, Event>.class);
IState<StateId, Event> mockState = Mockito.mock(IState.class<StateId, Event>);
Generics in java are implemented via type erasure. It means that parameterized classes are checked by the compiler, but at runtime all classes are "raw" (for retrocompatibility reasons). A consequence of this is that there is only one Class object representing IState
, and not an infinite number of classes corresponding to all possible parameters.
To disable the warning, add @SuppressWarning("unchecked")
just before the line.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With