Mocking the return value of System.currentTimeMillis() with JMockit
Having the ability to mock the return value of System.currentTimeMillis() can be very useful when testing time-sensitive code. The following is an example of how to accomplish the mocking of System.currentTimeMillis() to return any desired value, easily with JMockit 1.25.
import java.util.Date;
import mockit.Mock;
import mockit.MockUp;
public class Tester {
private static class SystemMock extends MockUp<System> {
@Mock
public static long currentTimeMillis() {
return 10000000L;
}
}
public void doSomethingWithDates() {
new SystemMock();
System.out.println(new Date());
}
public static void main(String args[]) {
Tester t = new Tester();
t.doSomethingWithDates();
}
}
Thanks to trunkc for providing the answer on this StackOverflow thread: http://stackoverflow.com/questions/31750244/jmockit-mocking-system-currenttimemillis