Droid_Interceptor
Droid_Interceptor

Reputation: 663

Mockito GregorianCalendate.getTime() causing error

I am trying to mock the return of GregorianCalendar.getTime() which should be a Date(). But am getting this error

org.mockito.exceptions.misusing.WrongTypeOfReturnValue: 
Date$$EnhancerByMockitoWithCGLIB$$91e3d4b7 cannot be returned by getTimeInMillis()
getTimeInMillis() should return long

Mockito.when(gregorianCalendar.getTime()).thenReturn(date);

Both gregorianCalendar and date are mocked objects.

Any advice on how to fix this? All help much appreciated

Upvotes: 5

Views: 1927

Answers (2)

AlexR
AlexR

Reputation: 115338

Take a look on implementation of getTime() that is located in super class of GregorianCalendar named Calendar:

public final Date getTime() {
    return new Date(getTimeInMillis());
}

This means that you should probably try to mock getTimeInMillis() instead:

Mockito.when(gregorianCalendar.getTimeInMillis()).thenReturn(date.getTime());

Upvotes: 7

Dawood ibn Kareem
Dawood ibn Kareem

Reputation: 79838

A GregorianCalendar is a value object. The best advice about mocking value objects is never to do so. Just create a real GregorianCalendar with the date that you want to use.

Upvotes: 0

Related Questions