49

我有一个使用当前时间进行一些计算的函数。我想用 mockito 来模拟它。

我想测试的类的一个例子:

public class ClassToTest {
    public long getDoubleTime(){
        return new Date().getTime()*2;
    }
}

我想要类似的东西:

@Test
public void testDoubleTime(){
   mockDateSomeHow(Date.class).when(getTime()).return(30);
   assertEquals(60,new ClassToTest().getDoubleTime());
}

可以嘲笑吗?我不想更改“已测试”代码以便进行测试。

4

7 回答 7

66

正确的做法是重构您的代码,使其更具可测试性,如下所示。重构您的代码以删除对 Date 的直接依赖将允许您为正常运行时和测试运行时注入不同的实现:

interface DateTime {
    Date getDate();
}

class DateTimeImpl implements DateTime {
    @Override
    public Date getDate() {
       return new Date();
    }
}

class MyClass {

    private final DateTime dateTime;
    // inject your Mock DateTime when testing other wise inject DateTimeImpl

    public MyClass(final DateTime dateTime) {
        this.dateTime = dateTime;
    }

    public long getDoubleTime(){
        return dateTime.getDate().getTime()*2;
    }
}

public class MyClassTest {
    private MyClass myClassTest;

    @Before
    public void setUp() {
        final Date date = Mockito.mock(Date.class);
        Mockito.when(date.getTime()).thenReturn(30L);

        final DateTime dt = Mockito.mock(DateTime.class);
        Mockito.when(dt.getDate()).thenReturn(date);

        myClassTest = new MyClass(dt);
    }

    @Test
    public void someTest() {
        final long doubleTime = myClassTest.getDoubleTime();
        assertEquals(60, doubleTime);
    }
}
于 2012-08-09T16:34:57.767 回答
26

如果您有无法重构且不想影响的遗留代码,请System.currentTimeMillis()尝试使用PowermockPowerMockito

//note the static import
import static org.powermock.api.mockito.PowerMockito.whenNew;

@PrepareForTest({ LegacyClassA.class, LegacyClassB.class })

@Before
public void setUp() throws Exception {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone("PST"));

    Date NOW = sdf.parse("2015-05-23 00:00:00");

    // everytime we call new Date() inside a method of any class
    // declared in @PrepareForTest we will get the NOW instance 
    whenNew(Date.class).withNoArguments().thenReturn(NOW);

}

public class LegacyClassA {
  public Date getSomeDate() {
     return new Date(); //returns NOW
  }
}
于 2015-05-23T17:06:16.770 回答
6

可以通过使用PowerMock来做到这一点,它增强了 Mockito 以模拟静态方法。然后你可以mockSystem.currentTimeMillis(),这是new Date()最终获得时间的地方。

可以。我不会就你是否应该提出意见。

于 2012-08-09T20:13:29.390 回答
1

一种不直接回答问题但可能解决潜在问题(具有可重复测试)的方法是允许Date作为测试参数并将委托添加到默认日期。

像这样

public class ClassToTest {

    public long getDoubleTime() {
      return getDoubleTime(new Date());
    }

    long getDoubleTime(Date date) {  // package visibility for tests
      return date.getTime() * 2;
    }
}

在生产代码中,您使用getDoubleTime()和测试getDoubleTime(Date date).

于 2016-07-05T16:49:02.920 回答
0

你也可以使用 jmockit 来模拟 new Date():

    @Test
    public void mockTime() {
        new MockUp<System>() {
            @Mock
            public long currentTimeMillis() {
                // Now is always 11/11/2021
                Date fake = new Date(121, Calendar.DECEMBER, 11);
                return fake.getTime();
            }
        };
        Assert.assertEquals("mock time failed", new Date(121, Calendar.DECEMBER, 11), new Date());
    }
于 2021-03-28T03:11:31.137 回答
0

new Date()使用和System.currentTimeMillis()使用 PowerMockito的工作示例。
这是Instance的示例。

@RunWith(PowerMockRunner.class)
@PrepareForTest(LegacyClass.class) // prepares byte-code of the LegacyClass
public class SystemTimeTest {
    
    private final Date fakeNow = Date.from(Instant.parse("2010-12-03T10:15:30.00Z"));

    @Before
    public void init() throws Exception {
        // mock new Date()
        PowerMockito.whenNew(Date.class).withNoArguments().thenReturn(fakeNow);
        System.out.println("Fake now: " + fakeNow);

        // mock System.currentTimeMillis()
        PowerMockito.mockStatic(System.class);
        PowerMockito.when(System.currentTimeMillis()).thenReturn(fakeNow.getTime());
        System.out.println("Fake currentTimeMillis: " + System.currentTimeMillis());
    }

    @Test
    public void legacyClass() {
        LegacyClass legacyClass = new LegacyClass();
        legacyClass.methodWithNewDate();
        legacyClass.methodWithCurrentTimeMillis();
    }

}

class LegacyClass {

    public void methodWithNewDate() {
        Date now = new Date();
        System.out.println("LegacyClass new Date() is " + now);
    }

    public void methodWithCurrentTimeMillis() {
        long now = System.currentTimeMillis();
        System.out.println("LegacyClass System.currentTimeMillis() is " + now);
    }

}

控制台输出

Fake now: Fri Dec 03 16:15:30 NOVT 2010
Fake currentTimeMillis: 1291371330000
LegacyClass new Date() is Fri Dec 03 16:15:30 NOVT 2010
LegacyClass System.currentTimeMillis() is 1291371330000
于 2021-04-02T14:20:24.593 回答
-1
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<Date>() {

        @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<Date>() {

        @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<Calendar>() {
        @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;
        }
    });
}
于 2018-04-10T10:14:29.177 回答