Skip to content

Instantly share code, notes, and snippets.

@wickkidd
Created January 6, 2020 17:30
Show Gist options
  • Save wickkidd/05453f0b20619e3862211a5872dae611 to your computer and use it in GitHub Desktop.
Save wickkidd/05453f0b20619e3862211a5872dae611 to your computer and use it in GitHub Desktop.
TimeCop::freezeDuring static method that freezes time during the execution of the passed lambda (Runnable). Idea stolen from my days as a ruby dev https://github.com/travisjeffery/timecop
package my.awesome.namespace;
import org.joda.time.DateTime;
import org.joda.time.DateTimeUtils;
public class TimeCop {
public static void freezeDuring(Runnable block) {
DateTimeUtils.setCurrentMillisFixed(DateTime.now().getMillis());
block.run();
DateTimeUtils.setCurrentMillisSystem();
};
}
// usage example
TimeUnit defaultUnit = TimeUnit.HOURS;
int defaultInterval = 1;
TimeCop.freezeDuring(() -> {
myDate = new Date(System.currentTimeMillis() + defaultUnit.toMillis(defaultInterval));
ClassUnderTest.someMethodThatTriggersADateCreationInAPrivateDelegateMethod();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment