How can i mock and Change time?
I use Calendar.getInstance() inside the Method under test
this is the method
public List<Object> chechAuth(){
Calendar from = Calendar.getInstance();
if(jobService.findJobByCheckAuth(from.getTime(), true).isEmpty()){
from.add(Calendar.YEAR, -10);
}
Calendar to = Calendar.getInstance();
to.add(Calendar.MONTH, 2);
System.out.println("from: "+from.getTime());
System.out.println("to: "+to.getTime());
return objectDAO.findAuth(from.getTime(), to.getTime());
}
when I use Calendar to = Calendar.getInstance(); it return a date different from July 02 2016
This is my test class:
@RunWith(PowerMockRunner.class)
@PrepareForTest({Calendar.class, ImpServiceTest.class})
public class ImpServiceTest {
@InjectMocks
private ImpService impService = new ImpServiceImpl();
@Before
public void setup(){
MockitoAnnotations.initMocks(this);
Calendar now = Calendar.getInstance();
now.set(2016, Calendar.JULY, 2 ,0,0,0);
PowerMockito.mockStatic(Calendar.class);
PowerMockito.when(Calendar.getInstance()).thenReturn(now);
}
@Test
public void methodTEST() throws Exception {
Calendar from = Calendar.getInstance();
when(jobService.findJobByCheckAuth(eq(now.getTime()), eq(true))).thenReturn(new ArrayList<Job>());
impService.chechAuth();
}
this code print
From: Sat Sep 02 00:00:00 CEST 2006
To: Sat Sep 02 00:00:00 CEST 2006
I want that the first Calendar.getInstance() return
Sun Jul 02 00:00:00 CEST 2006
and the second
Fri Sep 02 00:00:00 CEST 2016
some advice?