hammerfest hammerfest - 6 months ago 34
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

SomeTypeCollection<SomeType> someTypeCollectionMock;

SomeType 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)


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

T extends SomeOtherType 

is given in the method under test)

SomeOtherType someTypeMock;

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