Java or C# equivalent of Python freezegun or Ruby timecop

I want to test highly time dependent applications written in Java or C#.

Is there a Java or C# equivalent of Python freezegun or Ruby timecop?

Jon Skeet
people
quotationmark

You don't need a separate library to do testing of time-based code - you just need to treat "the current time provider" as a dependency like you would anything else. So avoid calls to new Date(), Calendar.getInstance() etc in Java, and DateTime.Now, DateTime.UtcNow etc in .NET. Instead, create a Clock or IClock interface for getting "the current time" and then create a normal implementation of it which does use the system clock, and a fake implementation which allows you to set the time. These are pretty trivial to write, and don't need third party libraries.

Inject the clock into any code that needs it as you would any other dependency, and then you can supply a fake one in your tests with no problems.

Indeed, in Java 8 you can use the java.time API (which is much better than using Date and Calendar) and has a Clock abstract class - which includes the idea of the time zone as well. In .NET I'd probably write a simple interface and implementation based on DateTime, but always using a UTC kind of DateTime. Or use my Noda Time project which comes with the IClock interface and a testing version.

people

See more on this question at Stackoverflow