How can I mock java.time.LocalDate.now()

In your code, replace LocalDate.now() with LocalDate.now(clock);. You can then pass Clock.systemDefaultZone() for production and a fixed clock for testing. This is an example : First, inject the Clock. If you are using spring boot just do a : @Bean public Clock clock() { return Clock.systemDefaultZone(); } Second, call LocalDate.now(clock) in your code : @Component … Read more

Override Java System.currentTimeMillis for testing time sensitive code

I strongly recommend that instead of messing with the system clock, you bite the bullet and refactor that legacy code to use a replaceable clock. Ideally that should be done with dependency injection, but even if you used a replaceable singleton you would gain testability. This could almost be automated with search and replace for … Read more

How can I set the System Time in Java?

Java doesn’t have an API to do this. Most system commands to do it require admin rights, so Runtime can’t help unless you run the whole process as administrator/root or you use runas/sudo. Depending on what you need, you can replace System.currentTimeMillis(). There are two approaches to this: Replace all calls to System.currentTimeMillis() with a … Read more

Unit Testing: DateTime.Now

The best strategy is to wrap the current time in an abstraction and inject that abstraction into the consumer. Alternatively, you can also define a time abstraction as an Ambient Context: public abstract class TimeProvider { private static TimeProvider current = DefaultTimeProvider.Instance; public static TimeProvider Current { get { return TimeProvider.current; } set { if … Read more