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

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