hammerfest hammerfest - 5 months ago 22
Java Question

Mockito casting to generics

A part of a method to be unit tested is as follows

SomeTypeCollection<SomeType> someTypeCollection = ...
T currentObject = null;
while( ( currentObject = (T) someTypeCollection.next() ) != null ) {...}


The relevant part of the unit test would be

@Mock
SomeTypeCollection<SomeType> someTypeCollectionMock;

@Mock
SomeType someTypeMock;

when(someTypeCollectionMock.next()).thenReturn(someTypeMock);


However, although the mocked next() call seems to succesfully return the mocked object, the casting fails with the following error

> SomeType$$EnhancerByMockitoWithCGILIB$$98474372 cannot be cast to (ActualTypeOfCurrentObject)

Answer

The issue can be overcome in Mockito using the following changes (assuming

T extends SomeOtherType 

is given in the method under test)

@Mock(extraInterfaces=SomeType.class)
SomeOtherType someTypeMock;

stub(someTypeCollectionMock.next()).toReturn((SomeType) someTypeMock).toReturn(null);