Mockito, mock and change Calendar.getIstance() [duplicate]

橙三吉。 提交于 2020-06-26 07:07:09

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/38148077/mockito-mock-and-change-calendar-getistance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!