2

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?

Community
  • 1
  • 1
Silvio Troia
  • 1,439
  • 19
  • 36

2 Answers2

3

You should annotate the test class with:

@RunWith(PowerMockRunner.class)
@PrepareForTest({Calendar.class, MyTest.class})

Where MyTest is the name of the class with tests. For powermockito to work you need to prepare for tests both the class being mocked as well as the target class.

I'm not sure if it is possible to prepare for tests the test class, so if it doesn't work move the Calendar code to other class.

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
1

You can do it like this:

@Test
public void methodTEST() throws Exception {

PowerMockito.mockStatic(Calendar.class);

    Calendar from = Calendar.getInstance();

   Date time = from.getTime();

Mockito.when(Calendar.getInstance()).thenReturn(from);

Mockito.when(from.getTime()).thenReturn(time);

    System.out.println(from.getTime());

    from.add(Calendar.YEAR, -1);

    System.out.println(Calendar.getInstance().getTime());
  }

Hope that helps.

Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39