2014-04-04 2 views
0

반환 나는 다음과 같은 단위 테스트가 있습니다mockito - 다음 오류

@Test 
public void testGenerateFileName(){ 

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

세 번째 줄에서 나는 다음과 같은 오류가 점점 오전 :

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. 

왜 이런 일이 있습니까? getTimeInMillis()을 사용하고 있지 않습니다.

답변

3

문제는 GregorianCalendar.getTime() 메서드가 final이므로 Mockito가 메서드 호출을 가로 채지 못하는 것입니다.

대안은 Calendar에 날짜를 변환하는 아파치 평민를 사용하여 lang을 사용하는 것입니다, 그래서 당신은 getTime를 호출 할 때 그것은 당신이, 당신이 PowerMock을 사용할 수 있습니다 야생 가고 싶은 경우

DateUtils.toCalendar(date) 

기대 값을 반환 최종 필드를 모의했지만, 더 간단한 대안이있을 때 PowerMock의 복잡성을 추가 할 가치가 없다고 생각합니다.

또 다른 요점. 소유하고 있지 않은 객체를 조롱하지 말아야한다. 이것은 단위 테스트와 모의 객체에 대한 중요한 점이다. 이 연습에 대한 링크가있는 것은 reference입니다.

마지막으로 프로젝트에 적용 할 수있는 것처럼 현재 시간을 얻을 수있는 곳에서 "시계"개체를 도입하는 것이 좋습니다. 테스트는이 시계를 조작하여 "정적"현재 시간을 반환 할 수 있습니다 .

편집

자바 8 Clock.fixed(), Clock.tick(), Clock.tickSeconds()Clock.tickMinutes()를 호출하는 것으로 취득 할 수 있습니다 테스트를위한 구체적인 구현에 이상적인이있는 Clock 추상화를 포함 ... 아니면 시계 당신 자신의 구현을 작성할 수 있습니다

.