Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java or C# equivalent of Python freezegun or Ruby timecop [closed]

Tags:

java

c#

time

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?

like image 446
user2602898 Avatar asked May 30 '15 04:05

user2602898


People also ask

Which is better Java or C?

C is more procedure-oriented. Java is more data-oriented. C is a middle-level language because binding of the gaps takes place between machine level language and high-level languages. Java is a high-level language because translation of code takes place into machine language using compiler or interpreter.

Is Java is easier than C?

1) Java is simpler, the syntax is much more readable than C, C++ or any other language. 2) Java is good to learn Object-Oriented programming, but not so good for procedural one, prefer C there.

Which is more important Java or C?

Both languages are most important,with the help of c language we,can build our logics and basic Programming concept are strong that's the really helpful for every programmers. before learning the java you can strong your basic and after that learn java.


1 Answers

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.

like image 67
Jon Skeet Avatar answered Oct 07 '22 01:10

Jon Skeet