hammerfest
hammerfest

Reputation: 2273

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)

Upvotes: 2

Views: 1978

Answers (2)

hammerfest
hammerfest

Reputation: 2273

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

Upvotes: 3

John B
John B

Reputation: 32949

You do not have an explicit relationship between T and SomeType. Therefore, how could SomeType be cast to T? For this to work T MUST be a super class of SomeType. This is not a Mockito issue, just straight Java.

According to the test I would have expected your method to look like this:

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

or

public <T super SomeType> void method(){
   SomeTypeCollection<SomeType> someTypeCollection = ...
   TcurrentObject = null;
   while( ( currentObject = (T) someTypeCollection.next() ) != null ) {...}
}

Upvotes: 0

Related Questions