문제

I have the following unit test:

@Test
public void testGenerateFileName(){

GregorianCalendar mockCalendar = Mockito.mock(GregorianCalendar.class);
Date date = new Date(1000);
Mockito.when(mockCalendar.getTime()).thenReturn(date);  
...
}

At the third line I am getting the following error:

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:  Date cannot be returned by getTimeInMillis() getTimeInMillis() should return long
*** If you're unsure why you're getting above error read on. Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.    Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies - 
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

Why is this happening? I'm not using getTimeInMillis().

도움이 되었습니까?

해결책

The problem is that the method GregorianCalendar.getTime() is final, so Mockito cannot intercept the method call.

An alternative is to use Apache commons lang to transform the date to a Calendar, so when you call getTime it returns the value you expect

DateUtils.toCalendar(date)

If you want to go wild, you can use PowerMock to mock final fields, but I think it's not worth adding the complexity of PowerMock, when you have a simpler alternative.

And another point. You should try to avoid mocking objects that you don't own, this is quite an important point about unit testing and mock objects. Here's one reference that has some links about this practice.

And last, as it might apply to your project: it's quite a good practice to introduce a "Clock" object from where you can get the current time, and tests can manipulate this clock to return a "static" current time.

Edit

Java 8 includes the Clock abstraction, which has concrete implementations ideal for testing which can be obtained by calling Clock.fixed(), Clock.tick(), Clock.tickSeconds() and Clock.tickMinutes()... Or you can write your own implementation of Clock.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top