How to mock new Date() in java using Mockito

前端 未结 5 1121
失恋的感觉
失恋的感觉 2020-11-29 05:21

I have a function that uses the current time to make some calculations. I\'d like to mock it using mockito.

An example of the class I\'d like to test:



        
5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 05:32

    Date now = new Date();    
    now.set(2018, Calendar.FEBRUARY, 15, 1, 0); // set date to 2018-02-15
    //set current time to 2018-02-15
    mockCurrentTime(now.getTimeInMillis());
    
    private void mockCurrentTime(long currTimeUTC) throws Exception {
        // mock new dates with current time
        PowerMockito.mockStatic(Date.class);
        PowerMockito.whenNew(Date.class).withNoArguments().thenAnswer(new Answer() {
    
            @Override
            public Date answer(InvocationOnMock invocation) throws Throwable {
                return new Date(currTimeUTC);
            }
        });
    
        //do not mock creation of specific dates
        PowerMockito.whenNew(Date.class).withArguments(anyLong()).thenAnswer(new Answer() {
    
            @Override
            public Date answer(InvocationOnMock invocation) throws Throwable {
                return new Date((long) invocation.getArguments()[0]);
            }
        });
    
        // mock new calendars created with time zone
        PowerMockito.mockStatic(Calendar.class);
        Mockito.when(Calendar.getInstance(any(TimeZone.class))).thenAnswer(new Answer() {
            @Override
            public Calendar answer(InvocationOnMock invocation) throws Throwable {
                TimeZone tz = invocation.getArgumentAt(0, TimeZone.class);
                Calendar cal = Calendar.getInstance(tz);
                cal.setTimeInMillis(currTimeUTC);
                return cal;
            }
        });
    }
    

提交回复
热议问题