Created
January 6, 2020 17:30
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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